# pylint: disable=line-too-long,useless-suppression,too-many-lines
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) Python Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from collections.abc import MutableMapping
import datetime
from io import IOBase
import json
from typing import Any, AsyncIterator, Callable, IO, Optional, TypeVar, Union, cast, overload
import urllib.parse

from azure.core import AsyncPipelineClient, MatchConditions
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
    ClientAuthenticationError,
    HttpResponseError,
    ResourceExistsError,
    ResourceModifiedError,
    ResourceNotFoundError,
    ResourceNotModifiedError,
    StreamClosedError,
    StreamConsumedError,
    map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import AsyncHttpResponse, HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling

from ... import models as _models
from ..._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize
from ..._utils.serialization import Deserializer, Serializer
from ..._utils.utils import ClientMixinABC
from ...operations._operations import (
    build_all_policies_list_by_service_request,
    build_api_create_or_update_request,
    build_api_delete_request,
    build_api_diagnostic_create_or_update_request,
    build_api_diagnostic_delete_request,
    build_api_diagnostic_get_entity_tag_request,
    build_api_diagnostic_get_request,
    build_api_diagnostic_list_by_service_request,
    build_api_diagnostic_update_request,
    build_api_export_get_request,
    build_api_gateway_config_connection_create_or_update_request,
    build_api_gateway_config_connection_delete_request,
    build_api_gateway_config_connection_get_request,
    build_api_gateway_config_connection_list_by_gateway_request,
    build_api_gateway_create_or_update_request,
    build_api_gateway_delete_request,
    build_api_gateway_get_request,
    build_api_gateway_hostname_binding_create_or_update_request,
    build_api_gateway_hostname_binding_delete_request,
    build_api_gateway_hostname_binding_get_request,
    build_api_gateway_hostname_binding_list_by_gateway_request,
    build_api_gateway_hostname_binding_refresh_secret_request,
    build_api_gateway_list_by_resource_group_request,
    build_api_gateway_list_request,
    build_api_gateway_update_request,
    build_api_get_entity_tag_request,
    build_api_get_request,
    build_api_issue_attachment_create_or_update_request,
    build_api_issue_attachment_delete_request,
    build_api_issue_attachment_get_entity_tag_request,
    build_api_issue_attachment_get_request,
    build_api_issue_attachment_list_by_service_request,
    build_api_issue_comment_create_or_update_request,
    build_api_issue_comment_delete_request,
    build_api_issue_comment_get_entity_tag_request,
    build_api_issue_comment_get_request,
    build_api_issue_comment_list_by_service_request,
    build_api_issue_create_or_update_request,
    build_api_issue_delete_request,
    build_api_issue_get_entity_tag_request,
    build_api_issue_get_request,
    build_api_issue_list_by_service_request,
    build_api_issue_update_request,
    build_api_list_by_service_request,
    build_api_list_by_tags_request,
    build_api_management_gateway_skus_list_available_skus_request,
    build_api_management_operations_list_request,
    build_api_management_perform_connectivity_check_async_request,
    build_api_management_service_apply_network_configuration_updates_request,
    build_api_management_service_backup_request,
    build_api_management_service_check_name_availability_request,
    build_api_management_service_create_or_update_request,
    build_api_management_service_delete_request,
    build_api_management_service_get_domain_ownership_identifier_request,
    build_api_management_service_get_request,
    build_api_management_service_get_sso_token_request,
    build_api_management_service_list_by_resource_group_request,
    build_api_management_service_list_request,
    build_api_management_service_migrate_to_stv2_request,
    build_api_management_service_refresh_hostnames_request,
    build_api_management_service_restore_request,
    build_api_management_service_skus_list_available_service_skus_request,
    build_api_management_service_update_request,
    build_api_management_skus_list_request,
    build_api_management_workspace_link_get_request,
    build_api_management_workspace_links_list_by_service_request,
    build_api_operation_create_or_update_request,
    build_api_operation_delete_request,
    build_api_operation_get_entity_tag_request,
    build_api_operation_get_request,
    build_api_operation_list_by_api_request,
    build_api_operation_policy_create_or_update_request,
    build_api_operation_policy_delete_request,
    build_api_operation_policy_get_entity_tag_request,
    build_api_operation_policy_get_request,
    build_api_operation_policy_list_by_operation_request,
    build_api_operation_update_request,
    build_api_policy_create_or_update_request,
    build_api_policy_delete_request,
    build_api_policy_get_entity_tag_request,
    build_api_policy_get_request,
    build_api_policy_list_by_api_request,
    build_api_product_list_by_apis_request,
    build_api_release_create_or_update_request,
    build_api_release_delete_request,
    build_api_release_get_entity_tag_request,
    build_api_release_get_request,
    build_api_release_list_by_service_request,
    build_api_release_update_request,
    build_api_revision_list_by_service_request,
    build_api_schema_create_or_update_request,
    build_api_schema_delete_request,
    build_api_schema_get_entity_tag_request,
    build_api_schema_get_request,
    build_api_schema_list_by_api_request,
    build_api_tag_description_create_or_update_request,
    build_api_tag_description_delete_request,
    build_api_tag_description_get_entity_tag_request,
    build_api_tag_description_get_request,
    build_api_tag_description_list_by_service_request,
    build_api_tool_create_or_update_request,
    build_api_tool_delete_request,
    build_api_tool_get_entity_tag_request,
    build_api_tool_get_request,
    build_api_tool_list_by_api_request,
    build_api_tool_update_request,
    build_api_update_request,
    build_api_version_set_create_or_update_request,
    build_api_version_set_delete_request,
    build_api_version_set_get_entity_tag_request,
    build_api_version_set_get_request,
    build_api_version_set_list_by_service_request,
    build_api_version_set_update_request,
    build_api_wiki_create_or_update_request,
    build_api_wiki_delete_request,
    build_api_wiki_get_entity_tag_request,
    build_api_wiki_get_request,
    build_api_wiki_update_request,
    build_api_wikis_list_request,
    build_authorization_access_policy_create_or_update_request,
    build_authorization_access_policy_delete_request,
    build_authorization_access_policy_get_request,
    build_authorization_access_policy_list_by_authorization_request,
    build_authorization_confirm_consent_code_request,
    build_authorization_create_or_update_request,
    build_authorization_delete_request,
    build_authorization_get_request,
    build_authorization_list_by_authorization_provider_request,
    build_authorization_login_links_post_request,
    build_authorization_provider_create_or_update_request,
    build_authorization_provider_delete_request,
    build_authorization_provider_get_request,
    build_authorization_provider_list_by_service_request,
    build_authorization_provider_refresh_secret_request,
    build_authorization_server_create_or_update_request,
    build_authorization_server_delete_request,
    build_authorization_server_get_entity_tag_request,
    build_authorization_server_get_request,
    build_authorization_server_list_by_service_request,
    build_authorization_server_list_secrets_request,
    build_authorization_server_update_request,
    build_backend_create_or_update_request,
    build_backend_delete_request,
    build_backend_get_entity_tag_request,
    build_backend_get_request,
    build_backend_list_by_service_request,
    build_backend_reconnect_request,
    build_backend_update_request,
    build_cache_create_or_update_request,
    build_cache_delete_request,
    build_cache_get_entity_tag_request,
    build_cache_get_request,
    build_cache_list_by_service_request,
    build_cache_update_request,
    build_certificate_create_or_update_request,
    build_certificate_delete_request,
    build_certificate_get_entity_tag_request,
    build_certificate_get_request,
    build_certificate_list_by_service_request,
    build_certificate_refresh_secret_request,
    build_client_application_create_or_update_request,
    build_client_application_delete_request,
    build_client_application_get_entity_tag_request,
    build_client_application_get_request,
    build_client_application_list_by_service_request,
    build_client_application_list_secrets_request,
    build_client_application_product_link_create_request,
    build_client_application_product_link_delete_request,
    build_client_application_product_link_get_request,
    build_client_application_product_link_list_by_client_applications_request,
    build_content_item_create_or_update_request,
    build_content_item_delete_request,
    build_content_item_get_entity_tag_request,
    build_content_item_get_request,
    build_content_item_list_by_service_request,
    build_content_type_create_or_update_request,
    build_content_type_delete_request,
    build_content_type_get_request,
    build_content_type_list_by_service_request,
    build_delegation_settings_create_or_update_request,
    build_delegation_settings_get_entity_tag_request,
    build_delegation_settings_get_request,
    build_delegation_settings_list_secrets_request,
    build_delegation_settings_update_request,
    build_deleted_services_get_by_name_request,
    build_deleted_services_list_by_subscription_request,
    build_deleted_services_purge_request,
    build_diagnostic_create_or_update_request,
    build_diagnostic_delete_request,
    build_diagnostic_get_entity_tag_request,
    build_diagnostic_get_request,
    build_diagnostic_list_by_service_request,
    build_diagnostic_update_request,
    build_documentation_create_or_update_request,
    build_documentation_delete_request,
    build_documentation_get_entity_tag_request,
    build_documentation_get_request,
    build_documentation_list_by_service_request,
    build_documentation_update_request,
    build_email_template_create_or_update_request,
    build_email_template_delete_request,
    build_email_template_get_entity_tag_request,
    build_email_template_get_request,
    build_email_template_list_by_service_request,
    build_email_template_update_request,
    build_gateway_api_create_or_update_request,
    build_gateway_api_delete_request,
    build_gateway_api_get_entity_tag_request,
    build_gateway_api_list_by_service_request,
    build_gateway_certificate_authority_create_or_update_request,
    build_gateway_certificate_authority_delete_request,
    build_gateway_certificate_authority_get_entity_tag_request,
    build_gateway_certificate_authority_get_request,
    build_gateway_certificate_authority_list_by_service_request,
    build_gateway_create_or_update_request,
    build_gateway_delete_request,
    build_gateway_generate_token_request,
    build_gateway_get_entity_tag_request,
    build_gateway_get_request,
    build_gateway_hostname_configuration_create_or_update_request,
    build_gateway_hostname_configuration_delete_request,
    build_gateway_hostname_configuration_get_entity_tag_request,
    build_gateway_hostname_configuration_get_request,
    build_gateway_hostname_configuration_list_by_service_request,
    build_gateway_invalidate_debug_credentials_request,
    build_gateway_list_by_service_request,
    build_gateway_list_debug_credentials_request,
    build_gateway_list_keys_request,
    build_gateway_list_trace_request,
    build_gateway_regenerate_key_request,
    build_gateway_update_request,
    build_global_schema_create_or_update_request,
    build_global_schema_delete_request,
    build_global_schema_get_entity_tag_request,
    build_global_schema_get_request,
    build_global_schema_list_by_service_request,
    build_graph_ql_api_resolver_create_or_update_request,
    build_graph_ql_api_resolver_delete_request,
    build_graph_ql_api_resolver_get_entity_tag_request,
    build_graph_ql_api_resolver_get_request,
    build_graph_ql_api_resolver_list_by_api_request,
    build_graph_ql_api_resolver_policy_create_or_update_request,
    build_graph_ql_api_resolver_policy_delete_request,
    build_graph_ql_api_resolver_policy_get_entity_tag_request,
    build_graph_ql_api_resolver_policy_get_request,
    build_graph_ql_api_resolver_policy_list_by_resolver_request,
    build_graph_ql_api_resolver_update_request,
    build_group_create_or_update_request,
    build_group_delete_request,
    build_group_get_entity_tag_request,
    build_group_get_request,
    build_group_list_by_service_request,
    build_group_update_request,
    build_group_user_check_entity_exists_request,
    build_group_user_create_request,
    build_group_user_delete_request,
    build_group_user_list_request,
    build_identity_provider_create_or_update_request,
    build_identity_provider_delete_request,
    build_identity_provider_get_entity_tag_request,
    build_identity_provider_get_request,
    build_identity_provider_list_by_service_request,
    build_identity_provider_list_secrets_request,
    build_identity_provider_update_request,
    build_issue_get_request,
    build_issue_list_by_service_request,
    build_logger_create_or_update_request,
    build_logger_delete_request,
    build_logger_get_entity_tag_request,
    build_logger_get_request,
    build_logger_list_by_service_request,
    build_logger_update_request,
    build_named_value_create_or_update_request,
    build_named_value_delete_request,
    build_named_value_get_entity_tag_request,
    build_named_value_get_request,
    build_named_value_list_by_service_request,
    build_named_value_list_value_request,
    build_named_value_refresh_secret_request,
    build_named_value_update_request,
    build_network_status_list_by_location_request,
    build_network_status_list_by_service_request,
    build_notification_create_or_update_request,
    build_notification_get_request,
    build_notification_list_by_service_request,
    build_notification_recipient_email_check_entity_exists_request,
    build_notification_recipient_email_create_or_update_request,
    build_notification_recipient_email_delete_request,
    build_notification_recipient_email_list_by_notification_request,
    build_notification_recipient_user_check_entity_exists_request,
    build_notification_recipient_user_create_or_update_request,
    build_notification_recipient_user_delete_request,
    build_notification_recipient_user_list_by_notification_request,
    build_open_id_connect_provider_create_or_update_request,
    build_open_id_connect_provider_delete_request,
    build_open_id_connect_provider_get_entity_tag_request,
    build_open_id_connect_provider_get_request,
    build_open_id_connect_provider_list_by_service_request,
    build_open_id_connect_provider_list_secrets_request,
    build_open_id_connect_provider_update_request,
    build_operation_list_by_tags_request,
    build_operation_status_get_request,
    build_operations_results_get_request,
    build_outbound_network_dependencies_endpoints_list_by_service_request,
    build_policy_create_or_update_request,
    build_policy_delete_request,
    build_policy_description_list_by_service_request,
    build_policy_fragment_create_or_update_request,
    build_policy_fragment_delete_request,
    build_policy_fragment_get_entity_tag_request,
    build_policy_fragment_get_request,
    build_policy_fragment_list_by_service_request,
    build_policy_fragment_list_references_request,
    build_policy_get_entity_tag_request,
    build_policy_get_request,
    build_policy_list_by_service_request,
    build_policy_restriction_create_or_update_request,
    build_policy_restriction_delete_request,
    build_policy_restriction_get_entity_tag_request,
    build_policy_restriction_get_request,
    build_policy_restriction_list_by_service_request,
    build_policy_restriction_update_request,
    build_policy_restriction_validations_by_service_request,
    build_portal_config_create_or_update_request,
    build_portal_config_get_entity_tag_request,
    build_portal_config_get_request,
    build_portal_config_list_by_service_request,
    build_portal_config_update_request,
    build_portal_revision_create_or_update_request,
    build_portal_revision_get_entity_tag_request,
    build_portal_revision_get_request,
    build_portal_revision_list_by_service_request,
    build_portal_revision_update_request,
    build_portal_settings_list_by_service_request,
    build_private_endpoint_connection_create_or_update_request,
    build_private_endpoint_connection_delete_request,
    build_private_endpoint_connection_get_by_name_request,
    build_private_endpoint_connection_get_private_link_resource_request,
    build_private_endpoint_connection_list_by_service_request,
    build_private_endpoint_connection_list_private_link_resources_request,
    build_product_api_check_entity_exists_request,
    build_product_api_create_or_update_request,
    build_product_api_delete_request,
    build_product_api_link_create_or_update_request,
    build_product_api_link_delete_request,
    build_product_api_link_get_request,
    build_product_api_link_list_by_product_request,
    build_product_api_list_by_product_request,
    build_product_create_or_update_request,
    build_product_delete_request,
    build_product_get_entity_tag_request,
    build_product_get_request,
    build_product_group_check_entity_exists_request,
    build_product_group_create_or_update_request,
    build_product_group_delete_request,
    build_product_group_link_create_or_update_request,
    build_product_group_link_delete_request,
    build_product_group_link_get_request,
    build_product_group_link_list_by_product_request,
    build_product_group_list_by_product_request,
    build_product_list_by_service_request,
    build_product_list_by_tags_request,
    build_product_policy_create_or_update_request,
    build_product_policy_delete_request,
    build_product_policy_get_entity_tag_request,
    build_product_policy_get_request,
    build_product_policy_list_by_product_request,
    build_product_subscriptions_list_request,
    build_product_update_request,
    build_product_wiki_create_or_update_request,
    build_product_wiki_delete_request,
    build_product_wiki_get_entity_tag_request,
    build_product_wiki_get_request,
    build_product_wiki_update_request,
    build_product_wikis_list_request,
    build_quota_by_counter_keys_list_by_service_request,
    build_quota_by_counter_keys_update_request,
    build_quota_by_period_keys_get_request,
    build_quota_by_period_keys_update_request,
    build_region_list_by_service_request,
    build_reports_list_by_api_request,
    build_reports_list_by_geo_request,
    build_reports_list_by_operation_request,
    build_reports_list_by_product_request,
    build_reports_list_by_request_request,
    build_reports_list_by_subscription_request,
    build_reports_list_by_time_request,
    build_reports_list_by_user_request,
    build_sign_in_settings_create_or_update_request,
    build_sign_in_settings_get_entity_tag_request,
    build_sign_in_settings_get_request,
    build_sign_in_settings_update_request,
    build_sign_up_settings_create_or_update_request,
    build_sign_up_settings_get_entity_tag_request,
    build_sign_up_settings_get_request,
    build_sign_up_settings_update_request,
    build_subscription_create_or_update_request,
    build_subscription_delete_request,
    build_subscription_get_entity_tag_request,
    build_subscription_get_request,
    build_subscription_list_request,
    build_subscription_list_secrets_request,
    build_subscription_regenerate_primary_key_request,
    build_subscription_regenerate_secondary_key_request,
    build_subscription_update_request,
    build_tag_api_link_create_or_update_request,
    build_tag_api_link_delete_request,
    build_tag_api_link_get_request,
    build_tag_api_link_list_by_product_request,
    build_tag_assign_to_api_request,
    build_tag_assign_to_operation_request,
    build_tag_assign_to_product_request,
    build_tag_create_or_update_request,
    build_tag_delete_request,
    build_tag_detach_from_api_request,
    build_tag_detach_from_operation_request,
    build_tag_detach_from_product_request,
    build_tag_get_by_api_request,
    build_tag_get_by_operation_request,
    build_tag_get_by_product_request,
    build_tag_get_entity_state_by_api_request,
    build_tag_get_entity_state_by_operation_request,
    build_tag_get_entity_state_by_product_request,
    build_tag_get_entity_state_request,
    build_tag_get_request,
    build_tag_list_by_api_request,
    build_tag_list_by_operation_request,
    build_tag_list_by_product_request,
    build_tag_list_by_service_request,
    build_tag_operation_link_create_or_update_request,
    build_tag_operation_link_delete_request,
    build_tag_operation_link_get_request,
    build_tag_operation_link_list_by_product_request,
    build_tag_product_link_create_or_update_request,
    build_tag_product_link_delete_request,
    build_tag_product_link_get_request,
    build_tag_product_link_list_by_product_request,
    build_tag_resource_list_by_service_request,
    build_tag_update_request,
    build_tenant_access_create_request,
    build_tenant_access_get_entity_tag_request,
    build_tenant_access_get_request,
    build_tenant_access_git_regenerate_primary_key_request,
    build_tenant_access_git_regenerate_secondary_key_request,
    build_tenant_access_list_by_service_request,
    build_tenant_access_list_secrets_request,
    build_tenant_access_regenerate_primary_key_request,
    build_tenant_access_regenerate_secondary_key_request,
    build_tenant_access_update_request,
    build_tenant_configuration_deploy_request,
    build_tenant_configuration_get_sync_state_request,
    build_tenant_configuration_save_request,
    build_tenant_configuration_validate_request,
    build_tenant_settings_get_request,
    build_tenant_settings_list_by_service_request,
    build_user_confirmation_password_send_request,
    build_user_create_or_update_request,
    build_user_delete_request,
    build_user_generate_sso_url_request,
    build_user_get_entity_tag_request,
    build_user_get_request,
    build_user_get_shared_access_token_request,
    build_user_group_list_request,
    build_user_identities_list_request,
    build_user_list_by_service_request,
    build_user_subscription_get_request,
    build_user_subscription_list_request,
    build_user_update_request,
    build_workspace_api_create_or_update_request,
    build_workspace_api_delete_request,
    build_workspace_api_diagnostic_create_or_update_request,
    build_workspace_api_diagnostic_delete_request,
    build_workspace_api_diagnostic_get_entity_tag_request,
    build_workspace_api_diagnostic_get_request,
    build_workspace_api_diagnostic_list_by_workspace_request,
    build_workspace_api_diagnostic_update_request,
    build_workspace_api_export_get_request,
    build_workspace_api_get_entity_tag_request,
    build_workspace_api_get_request,
    build_workspace_api_list_by_service_request,
    build_workspace_api_operation_create_or_update_request,
    build_workspace_api_operation_delete_request,
    build_workspace_api_operation_get_entity_tag_request,
    build_workspace_api_operation_get_request,
    build_workspace_api_operation_list_by_api_request,
    build_workspace_api_operation_policy_create_or_update_request,
    build_workspace_api_operation_policy_delete_request,
    build_workspace_api_operation_policy_get_entity_tag_request,
    build_workspace_api_operation_policy_get_request,
    build_workspace_api_operation_policy_list_by_operation_request,
    build_workspace_api_operation_update_request,
    build_workspace_api_policy_create_or_update_request,
    build_workspace_api_policy_delete_request,
    build_workspace_api_policy_get_entity_tag_request,
    build_workspace_api_policy_get_request,
    build_workspace_api_policy_list_by_api_request,
    build_workspace_api_release_create_or_update_request,
    build_workspace_api_release_delete_request,
    build_workspace_api_release_get_entity_tag_request,
    build_workspace_api_release_get_request,
    build_workspace_api_release_list_by_service_request,
    build_workspace_api_release_update_request,
    build_workspace_api_revision_list_by_service_request,
    build_workspace_api_schema_create_or_update_request,
    build_workspace_api_schema_delete_request,
    build_workspace_api_schema_get_entity_tag_request,
    build_workspace_api_schema_get_request,
    build_workspace_api_schema_list_by_api_request,
    build_workspace_api_update_request,
    build_workspace_api_version_set_create_or_update_request,
    build_workspace_api_version_set_delete_request,
    build_workspace_api_version_set_get_entity_tag_request,
    build_workspace_api_version_set_get_request,
    build_workspace_api_version_set_list_by_service_request,
    build_workspace_api_version_set_update_request,
    build_workspace_backend_create_or_update_request,
    build_workspace_backend_delete_request,
    build_workspace_backend_get_entity_tag_request,
    build_workspace_backend_get_request,
    build_workspace_backend_list_by_workspace_request,
    build_workspace_backend_update_request,
    build_workspace_certificate_create_or_update_request,
    build_workspace_certificate_delete_request,
    build_workspace_certificate_get_entity_tag_request,
    build_workspace_certificate_get_request,
    build_workspace_certificate_list_by_workspace_request,
    build_workspace_certificate_refresh_secret_request,
    build_workspace_create_or_update_request,
    build_workspace_delete_request,
    build_workspace_diagnostic_create_or_update_request,
    build_workspace_diagnostic_delete_request,
    build_workspace_diagnostic_get_entity_tag_request,
    build_workspace_diagnostic_get_request,
    build_workspace_diagnostic_list_by_workspace_request,
    build_workspace_diagnostic_update_request,
    build_workspace_get_entity_tag_request,
    build_workspace_get_request,
    build_workspace_global_schema_create_or_update_request,
    build_workspace_global_schema_delete_request,
    build_workspace_global_schema_get_entity_tag_request,
    build_workspace_global_schema_get_request,
    build_workspace_global_schema_list_by_service_request,
    build_workspace_group_create_or_update_request,
    build_workspace_group_delete_request,
    build_workspace_group_get_entity_tag_request,
    build_workspace_group_get_request,
    build_workspace_group_list_by_service_request,
    build_workspace_group_update_request,
    build_workspace_group_user_check_entity_exists_request,
    build_workspace_group_user_create_request,
    build_workspace_group_user_delete_request,
    build_workspace_group_user_list_request,
    build_workspace_list_by_service_request,
    build_workspace_logger_create_or_update_request,
    build_workspace_logger_delete_request,
    build_workspace_logger_get_entity_tag_request,
    build_workspace_logger_get_request,
    build_workspace_logger_list_by_workspace_request,
    build_workspace_logger_update_request,
    build_workspace_named_value_create_or_update_request,
    build_workspace_named_value_delete_request,
    build_workspace_named_value_get_entity_tag_request,
    build_workspace_named_value_get_request,
    build_workspace_named_value_list_by_service_request,
    build_workspace_named_value_list_value_request,
    build_workspace_named_value_refresh_secret_request,
    build_workspace_named_value_update_request,
    build_workspace_notification_create_or_update_request,
    build_workspace_notification_get_request,
    build_workspace_notification_list_by_service_request,
    build_workspace_notification_recipient_email_check_entity_exists_request,
    build_workspace_notification_recipient_email_create_or_update_request,
    build_workspace_notification_recipient_email_delete_request,
    build_workspace_notification_recipient_email_list_by_notification_request,
    build_workspace_notification_recipient_user_check_entity_exists_request,
    build_workspace_notification_recipient_user_create_or_update_request,
    build_workspace_notification_recipient_user_delete_request,
    build_workspace_notification_recipient_user_list_by_notification_request,
    build_workspace_policy_create_or_update_request,
    build_workspace_policy_delete_request,
    build_workspace_policy_fragment_create_or_update_request,
    build_workspace_policy_fragment_delete_request,
    build_workspace_policy_fragment_get_entity_tag_request,
    build_workspace_policy_fragment_get_request,
    build_workspace_policy_fragment_list_by_service_request,
    build_workspace_policy_fragment_list_references_request,
    build_workspace_policy_get_entity_tag_request,
    build_workspace_policy_get_request,
    build_workspace_policy_list_by_api_request,
    build_workspace_product_api_link_create_or_update_request,
    build_workspace_product_api_link_delete_request,
    build_workspace_product_api_link_get_request,
    build_workspace_product_api_link_list_by_product_request,
    build_workspace_product_create_or_update_request,
    build_workspace_product_delete_request,
    build_workspace_product_get_entity_tag_request,
    build_workspace_product_get_request,
    build_workspace_product_group_link_create_or_update_request,
    build_workspace_product_group_link_delete_request,
    build_workspace_product_group_link_get_request,
    build_workspace_product_group_link_list_by_product_request,
    build_workspace_product_list_by_service_request,
    build_workspace_product_policy_create_or_update_request,
    build_workspace_product_policy_delete_request,
    build_workspace_product_policy_get_entity_tag_request,
    build_workspace_product_policy_get_request,
    build_workspace_product_policy_list_by_product_request,
    build_workspace_product_update_request,
    build_workspace_subscription_create_or_update_request,
    build_workspace_subscription_delete_request,
    build_workspace_subscription_get_entity_tag_request,
    build_workspace_subscription_get_request,
    build_workspace_subscription_list_request,
    build_workspace_subscription_list_secrets_request,
    build_workspace_subscription_regenerate_primary_key_request,
    build_workspace_subscription_regenerate_secondary_key_request,
    build_workspace_subscription_update_request,
    build_workspace_tag_api_link_create_or_update_request,
    build_workspace_tag_api_link_delete_request,
    build_workspace_tag_api_link_get_request,
    build_workspace_tag_api_link_list_by_product_request,
    build_workspace_tag_create_or_update_request,
    build_workspace_tag_delete_request,
    build_workspace_tag_get_entity_state_request,
    build_workspace_tag_get_request,
    build_workspace_tag_list_by_service_request,
    build_workspace_tag_operation_link_create_or_update_request,
    build_workspace_tag_operation_link_delete_request,
    build_workspace_tag_operation_link_get_request,
    build_workspace_tag_operation_link_list_by_product_request,
    build_workspace_tag_product_link_create_or_update_request,
    build_workspace_tag_product_link_delete_request,
    build_workspace_tag_product_link_get_request,
    build_workspace_tag_product_link_list_by_product_request,
    build_workspace_tag_update_request,
    build_workspace_update_request,
)
from .._configuration import ApiManagementClientConfiguration

JSON = MutableMapping[str, Any]
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]]
List = list


class WorkspaceApiOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`workspace_api` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, workspace_id: str, api_id: str, **kwargs: Any
    ) -> _models.ApiContract:
        """Gets the details of the API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :return: ApiContract. The ApiContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ApiContract] = kwargs.pop("cls", None)

        _request = build_workspace_api_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            api_id=api_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ApiContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, workspace_id: str, api_id: str, **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_api_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            api_id=api_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    async def _create_or_update_initial(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        parameters: Union[_models.ApiCreateOrUpdateParameter, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_api_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            api_id=api_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["Azure-AsyncOperation"] = self._deserialize(
            "str", response.headers.get("Azure-AsyncOperation")
        )
        response_headers["location"] = self._deserialize("str", response.headers.get("location"))
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        parameters: _models.ApiCreateOrUpdateParameter,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiContract]:
        """Creates new or updates existing specified API of the workspace in an API Management service
        instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiCreateOrUpdateParameter
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns ApiContract. The ApiContract is compatible
         with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiContract]:
        """Creates new or updates existing specified API of the workspace in an API Management service
        instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns ApiContract. The ApiContract is compatible
         with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiContract]:
        """Creates new or updates existing specified API of the workspace in an API Management service
        instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns ApiContract. The ApiContract is compatible
         with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        parameters: Union[_models.ApiCreateOrUpdateParameter, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiContract]:
        """Creates new or updates existing specified API of the workspace in an API Management service
        instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param parameters: Create or update parameters. Is one of the following types:
         ApiCreateOrUpdateParameter, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiCreateOrUpdateParameter or JSON or
         IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns ApiContract. The ApiContract is compatible
         with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ApiContract] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._create_or_update_initial(
                resource_group_name=resource_group_name,
                service_name=service_name,
                workspace_id=workspace_id,
                api_id=api_id,
                parameters=parameters,
                etag=etag,
                match_condition=match_condition,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response_headers = {}
            response = pipeline_response.http_response
            response_headers["Azure-AsyncOperation"] = self._deserialize(
                "str", response.headers.get("Azure-AsyncOperation")
            )
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

            deserialized = _deserialize(_models.ApiContract, response.json())
            if cls:
                return cls(pipeline_response, deserialized, response_headers)  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.ApiContract].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.ApiContract](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        parameters: _models.ApiUpdateContract,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ApiContract:
        """Updates the specified API of the workspace in an API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param parameters: API Update Contract parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiUpdateContract
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ApiContract. The ApiContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ApiContract:
        """Updates the specified API of the workspace in an API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param parameters: API Update Contract parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ApiContract. The ApiContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ApiContract:
        """Updates the specified API of the workspace in an API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param parameters: API Update Contract parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ApiContract. The ApiContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        parameters: Union[_models.ApiUpdateContract, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.ApiContract:
        """Updates the specified API of the workspace in an API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param parameters: API Update Contract parameters. Is one of the following types:
         ApiUpdateContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiUpdateContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ApiContract. The ApiContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ApiContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_api_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            api_id=api_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ApiContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        delete_revisions: Optional[bool] = None,
        **kwargs: Any
    ) -> None:
        """Deletes the specified API of the workspace in an API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword delete_revisions: Delete all revisions of the Api. Default value is None.
        :paramtype delete_revisions: bool
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_api_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            api_id=api_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            delete_revisions=delete_revisions,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        tags: Optional[str] = None,
        expand_api_version_set: Optional[bool] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.ApiContract"]:
        """Lists all APIs of the workspace in an API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         displayName | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>| description | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
         endswith |</br>| serviceUrl | filter | ge, le, eq, ne, gt, lt | substringof, contains,
         startswith, endswith |</br>| path | filter | ge, le, eq, ne, gt, lt | substringof, contains,
         startswith, endswith |</br>| isCurrent | filter | eq, ne |  |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :keyword tags: Include tags in the response. Default value is None.
        :paramtype tags: str
        :keyword expand_api_version_set: Include full ApiVersionSet resource in response. Default value
         is None.
        :paramtype expand_api_version_set: bool
        :return: An iterator like instance of ApiContract
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ApiContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ApiContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_workspace_api_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    workspace_id=workspace_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    tags=tags,
                    expand_api_version_set=expand_api_version_set,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ApiContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class WorkspaceApiReleaseOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`workspace_api_release` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        release_id: str,
        **kwargs: Any
    ) -> _models.ApiReleaseContract:
        """Returns the details of an API release.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param release_id: Release identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type release_id: str
        :return: ApiReleaseContract. The ApiReleaseContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiReleaseContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ApiReleaseContract] = kwargs.pop("cls", None)

        _request = build_workspace_api_release_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            api_id=api_id,
            release_id=release_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ApiReleaseContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        release_id: str,
        **kwargs: Any
    ) -> bool:
        """Returns the etag of an API release.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param release_id: Release identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type release_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_api_release_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            api_id=api_id,
            release_id=release_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        release_id: str,
        parameters: _models.ApiReleaseContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ApiReleaseContract:
        """Creates a new Release for the API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param release_id: Release identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type release_id: str
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiReleaseContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ApiReleaseContract. The ApiReleaseContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiReleaseContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        release_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ApiReleaseContract:
        """Creates a new Release for the API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param release_id: Release identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type release_id: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ApiReleaseContract. The ApiReleaseContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiReleaseContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        release_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ApiReleaseContract:
        """Creates a new Release for the API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param release_id: Release identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type release_id: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ApiReleaseContract. The ApiReleaseContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiReleaseContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        release_id: str,
        parameters: Union[_models.ApiReleaseContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ApiReleaseContract:
        """Creates a new Release for the API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param release_id: Release identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type release_id: str
        :param parameters: Create parameters. Is one of the following types: ApiReleaseContract, JSON,
         IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiReleaseContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ApiReleaseContract. The ApiReleaseContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiReleaseContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ApiReleaseContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_api_release_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            api_id=api_id,
            release_id=release_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 200:
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if response.status_code == 201:
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ApiReleaseContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        release_id: str,
        parameters: _models.ApiReleaseContract,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ApiReleaseContract:
        """Updates the details of the release of the API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param release_id: Release identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type release_id: str
        :param parameters: API Release Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiReleaseContract
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ApiReleaseContract. The ApiReleaseContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiReleaseContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        release_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ApiReleaseContract:
        """Updates the details of the release of the API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param release_id: Release identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type release_id: str
        :param parameters: API Release Update parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ApiReleaseContract. The ApiReleaseContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiReleaseContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        release_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ApiReleaseContract:
        """Updates the details of the release of the API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param release_id: Release identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type release_id: str
        :param parameters: API Release Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ApiReleaseContract. The ApiReleaseContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiReleaseContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        release_id: str,
        parameters: Union[_models.ApiReleaseContract, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.ApiReleaseContract:
        """Updates the details of the release of the API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param release_id: Release identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type release_id: str
        :param parameters: API Release Update parameters. Is one of the following types:
         ApiReleaseContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiReleaseContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ApiReleaseContract. The ApiReleaseContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiReleaseContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ApiReleaseContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_api_release_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            api_id=api_id,
            release_id=release_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ApiReleaseContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        release_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes the specified release in the API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param release_id: Release identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type release_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_api_release_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            api_id=api_id,
            release_id=release_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.ApiReleaseContract"]:
        """Lists all releases of an API. An API release is created when making an API Revision current.
        Releases are also used to rollback to previous revisions. Results will be paged and can be
        constrained by the $top and $skip parameters.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| notes |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of ApiReleaseContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ApiReleaseContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ApiReleaseContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_workspace_api_release_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    workspace_id=workspace_id,
                    api_id=api_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ApiReleaseContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class WorkspaceApiOperationOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`workspace_api_operation` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        operation_id: str,
        **kwargs: Any
    ) -> _models.OperationContract:
        """Gets the details of the API Operation specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :return: OperationContract. The OperationContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.OperationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.OperationContract] = kwargs.pop("cls", None)

        _request = build_workspace_api_operation_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            api_id=api_id,
            operation_id=operation_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.OperationContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        operation_id: str,
        **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the API operation specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_api_operation_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            api_id=api_id,
            operation_id=operation_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        operation_id: str,
        parameters: _models.OperationContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.OperationContract:
        """Creates a new operation in the API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.OperationContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: OperationContract. The OperationContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.OperationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        operation_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.OperationContract:
        """Creates a new operation in the API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: OperationContract. The OperationContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.OperationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        operation_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.OperationContract:
        """Creates a new operation in the API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: OperationContract. The OperationContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.OperationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        operation_id: str,
        parameters: Union[_models.OperationContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.OperationContract:
        """Creates a new operation in the API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :param parameters: Create parameters. Is one of the following types: OperationContract, JSON,
         IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.OperationContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: OperationContract. The OperationContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.OperationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.OperationContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_api_operation_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            api_id=api_id,
            operation_id=operation_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 200:
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if response.status_code == 201:
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.OperationContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        operation_id: str,
        parameters: _models.OperationUpdateContract,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.OperationContract:
        """Updates the details of the operation in the API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :param parameters: API Operation Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.OperationUpdateContract
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: OperationContract. The OperationContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.OperationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        operation_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.OperationContract:
        """Updates the details of the operation in the API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :param parameters: API Operation Update parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: OperationContract. The OperationContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.OperationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        operation_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.OperationContract:
        """Updates the details of the operation in the API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :param parameters: API Operation Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: OperationContract. The OperationContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.OperationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        operation_id: str,
        parameters: Union[_models.OperationUpdateContract, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.OperationContract:
        """Updates the details of the operation in the API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :param parameters: API Operation Update parameters. Is one of the following types:
         OperationUpdateContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.OperationUpdateContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: OperationContract. The OperationContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.OperationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.OperationContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_api_operation_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            api_id=api_id,
            operation_id=operation_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.OperationContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        operation_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes the specified operation in the API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_api_operation_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            api_id=api_id,
            operation_id=operation_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_api(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        tags: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.OperationContract"]:
        """Lists a collection of the operations for the specified API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         displayName | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>| method | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>| description | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
         endswith |</br>| urlTemplate | filter | ge, le, eq, ne, gt, lt | substringof, contains,
         startswith, endswith |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :keyword tags: Include tags in the response. Default value is None.
        :paramtype tags: str
        :return: An iterator like instance of OperationContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.OperationContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.OperationContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_workspace_api_operation_list_by_api_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    workspace_id=workspace_id,
                    api_id=api_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    tags=tags,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.OperationContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class GraphQLApiResolverPolicyOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`graph_ql_api_resolver_policy` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        resolver_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        *,
        format: Optional[Union[str, _models.PolicyExportFormat]] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Get the policy configuration at the GraphQL API Resolver level.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param resolver_id: Resolver identifier within a GraphQL API. Must be unique in the current API
         Management service instance. Required.
        :type resolver_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :keyword format: Policy Export Format. Known values are: "xml" and "rawxml". Default value is
         None.
        :paramtype format: str or ~azure.mgmt.apimanagement.models.PolicyExportFormat
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.PolicyContract] = kwargs.pop("cls", None)

        _request = build_graph_ql_api_resolver_policy_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            resolver_id=resolver_id,
            policy_id=policy_id,
            subscription_id=self._config.subscription_id,
            format=format,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PolicyContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        resolver_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the GraphQL API resolver policy specified by its
        identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param resolver_id: Resolver identifier within a GraphQL API. Must be unique in the current API
         Management service instance. Required.
        :type resolver_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_graph_ql_api_resolver_policy_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            resolver_id=resolver_id,
            policy_id=policy_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        resolver_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        parameters: _models.PolicyContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Creates or updates policy configuration for the GraphQL API Resolver level.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param resolver_id: Resolver identifier within a GraphQL API. Must be unique in the current API
         Management service instance. Required.
        :type resolver_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :param parameters: The policy contents to apply. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PolicyContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        resolver_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Creates or updates policy configuration for the GraphQL API Resolver level.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param resolver_id: Resolver identifier within a GraphQL API. Must be unique in the current API
         Management service instance. Required.
        :type resolver_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :param parameters: The policy contents to apply. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        resolver_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Creates or updates policy configuration for the GraphQL API Resolver level.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param resolver_id: Resolver identifier within a GraphQL API. Must be unique in the current API
         Management service instance. Required.
        :type resolver_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :param parameters: The policy contents to apply. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        resolver_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        parameters: Union[_models.PolicyContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Creates or updates policy configuration for the GraphQL API Resolver level.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param resolver_id: Resolver identifier within a GraphQL API. Must be unique in the current API
         Management service instance. Required.
        :type resolver_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :param parameters: The policy contents to apply. Is one of the following types: PolicyContract,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PolicyContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.PolicyContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_graph_ql_api_resolver_policy_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            resolver_id=resolver_id,
            policy_id=policy_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PolicyContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        resolver_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes the policy configuration at the GraphQL Api Resolver.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param resolver_id: Resolver identifier within a GraphQL API. Must be unique in the current API
         Management service instance. Required.
        :type resolver_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_graph_ql_api_resolver_policy_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            resolver_id=resolver_id,
            policy_id=policy_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_resolver(
        self, resource_group_name: str, service_name: str, api_id: str, resolver_id: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.PolicyContract"]:
        """Get the list of policy configuration at the GraphQL API Resolver level.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param resolver_id: Resolver identifier within a GraphQL API. Must be unique in the current API
         Management service instance. Required.
        :type resolver_id: str
        :return: An iterator like instance of PolicyContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.PolicyContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.PolicyContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_graph_ql_api_resolver_policy_list_by_resolver_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    api_id=api_id,
                    resolver_id=resolver_id,
                    subscription_id=self._config.subscription_id,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.PolicyContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class ApiPolicyOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`api_policy` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        *,
        format: Optional[Union[str, _models.PolicyExportFormat]] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Get the policy configuration at the API level.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :keyword format: Policy Export Format. Known values are: "xml" and "rawxml". Default value is
         None.
        :paramtype format: str or ~azure.mgmt.apimanagement.models.PolicyExportFormat
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.PolicyContract] = kwargs.pop("cls", None)

        _request = build_api_policy_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            policy_id=policy_id,
            subscription_id=self._config.subscription_id,
            format=format,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PolicyContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the API policy specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_api_policy_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            policy_id=policy_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        parameters: _models.PolicyContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Creates or updates policy configuration for the API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :param parameters: The policy contents to apply. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PolicyContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Creates or updates policy configuration for the API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :param parameters: The policy contents to apply. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Creates or updates policy configuration for the API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :param parameters: The policy contents to apply. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        parameters: Union[_models.PolicyContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Creates or updates policy configuration for the API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :param parameters: The policy contents to apply. Is one of the following types: PolicyContract,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PolicyContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.PolicyContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_api_policy_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            policy_id=policy_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PolicyContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes the policy configuration at the Api.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_api_policy_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            policy_id=policy_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace_async
    async def list_by_api(
        self, resource_group_name: str, service_name: str, api_id: str, **kwargs: Any
    ) -> _models.PolicyCollection:
        """Get the policy configuration at the API level.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :return: PolicyCollection. The PolicyCollection is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyCollection
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.PolicyCollection] = kwargs.pop("cls", None)

        _request = build_api_policy_list_by_api_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PolicyCollection, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class PolicyOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`policy` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self,
        resource_group_name: str,
        service_name: str,
        policy_id: Union[str, _models.PolicyIdName],
        *,
        format: Optional[Union[str, _models.PolicyExportFormat]] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Get the Global policy definition of the Api Management service.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :keyword format: Policy Export Format. Known values are: "xml" and "rawxml". Default value is
         None.
        :paramtype format: str or ~azure.mgmt.apimanagement.models.PolicyExportFormat
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.PolicyContract] = kwargs.pop("cls", None)

        _request = build_policy_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            policy_id=policy_id,
            subscription_id=self._config.subscription_id,
            format=format,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PolicyContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, policy_id: Union[str, _models.PolicyIdName], **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the Global policy definition in the Api Management
        service.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_policy_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            policy_id=policy_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        policy_id: Union[str, _models.PolicyIdName],
        parameters: _models.PolicyContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Creates or updates the global policy configuration of the Api Management service.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :param parameters: The policy contents to apply. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PolicyContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        policy_id: Union[str, _models.PolicyIdName],
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Creates or updates the global policy configuration of the Api Management service.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :param parameters: The policy contents to apply. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        policy_id: Union[str, _models.PolicyIdName],
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Creates or updates the global policy configuration of the Api Management service.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :param parameters: The policy contents to apply. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        policy_id: Union[str, _models.PolicyIdName],
        parameters: Union[_models.PolicyContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Creates or updates the global policy configuration of the Api Management service.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :param parameters: The policy contents to apply. Is one of the following types: PolicyContract,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PolicyContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.PolicyContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_policy_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            policy_id=policy_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PolicyContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        policy_id: Union[str, _models.PolicyIdName],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes the global policy configuration of the Api Management Service.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_policy_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            policy_id=policy_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self, resource_group_name: str, service_name: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.PolicyContract"]:
        """Lists all the Global Policy definitions of the Api Management service.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :return: An iterator like instance of PolicyContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.PolicyContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.PolicyContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_policy_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.PolicyContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class ProductPolicyOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`product_policy` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        *,
        format: Optional[Union[str, _models.PolicyExportFormat]] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Get the policy configuration at the Product level.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :keyword format: Policy Export Format. Known values are: "xml" and "rawxml". Default value is
         None.
        :paramtype format: str or ~azure.mgmt.apimanagement.models.PolicyExportFormat
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.PolicyContract] = kwargs.pop("cls", None)

        _request = build_product_policy_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            product_id=product_id,
            policy_id=policy_id,
            subscription_id=self._config.subscription_id,
            format=format,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PolicyContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        **kwargs: Any
    ) -> bool:
        """Get the ETag of the policy configuration at the Product level.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_product_policy_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            product_id=product_id,
            policy_id=policy_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        parameters: _models.PolicyContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Creates or updates policy configuration for the Product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :param parameters: The policy contents to apply. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PolicyContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Creates or updates policy configuration for the Product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :param parameters: The policy contents to apply. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Creates or updates policy configuration for the Product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :param parameters: The policy contents to apply. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        parameters: Union[_models.PolicyContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Creates or updates policy configuration for the Product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :param parameters: The policy contents to apply. Is one of the following types: PolicyContract,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PolicyContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.PolicyContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_product_policy_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            product_id=product_id,
            policy_id=policy_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PolicyContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes the policy configuration at the Product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_product_policy_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            product_id=product_id,
            policy_id=policy_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_product(
        self, resource_group_name: str, service_name: str, product_id: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.PolicyContract"]:
        """Get the policy configuration at the Product level.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :return: An iterator like instance of PolicyContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.PolicyContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.PolicyContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_product_policy_list_by_product_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    product_id=product_id,
                    subscription_id=self._config.subscription_id,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.PolicyContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class WorkspacePolicyOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`workspace_policy` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        *,
        format: Optional[Union[str, _models.PolicyExportFormat]] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Get the policy configuration at the API level.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :keyword format: Policy Export Format. Known values are: "xml" and "rawxml". Default value is
         None.
        :paramtype format: str or ~azure.mgmt.apimanagement.models.PolicyExportFormat
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.PolicyContract] = kwargs.pop("cls", None)

        _request = build_workspace_policy_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            policy_id=policy_id,
            subscription_id=self._config.subscription_id,
            format=format,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PolicyContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the workspace policy specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_policy_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            policy_id=policy_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        parameters: _models.PolicyContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Creates or updates policy configuration for the workspace.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :param parameters: The policy contents to apply. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PolicyContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Creates or updates policy configuration for the workspace.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :param parameters: The policy contents to apply. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Creates or updates policy configuration for the workspace.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :param parameters: The policy contents to apply. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        parameters: Union[_models.PolicyContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Creates or updates policy configuration for the workspace.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :param parameters: The policy contents to apply. Is one of the following types: PolicyContract,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PolicyContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.PolicyContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_policy_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            policy_id=policy_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PolicyContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes the policy configuration at the workspace.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_policy_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            policy_id=policy_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_api(
        self, resource_group_name: str, service_name: str, workspace_id: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.PolicyContract"]:
        """Get the policy configuration at the workspace level.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :return: An iterator like instance of PolicyContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.PolicyContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.PolicyContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_workspace_policy_list_by_api_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    workspace_id=workspace_id,
                    subscription_id=self._config.subscription_id,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.PolicyContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class WorkspaceApiOperationPolicyOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`workspace_api_operation_policy` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        operation_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        *,
        format: Optional[Union[str, _models.PolicyExportFormat]] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Get the policy configuration at the API Operation level.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :keyword format: Policy Export Format. Known values are: "xml" and "rawxml". Default value is
         None.
        :paramtype format: str or ~azure.mgmt.apimanagement.models.PolicyExportFormat
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.PolicyContract] = kwargs.pop("cls", None)

        _request = build_workspace_api_operation_policy_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            api_id=api_id,
            operation_id=operation_id,
            policy_id=policy_id,
            subscription_id=self._config.subscription_id,
            format=format,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PolicyContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        operation_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the API operation policy specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_api_operation_policy_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            api_id=api_id,
            operation_id=operation_id,
            policy_id=policy_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        operation_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        parameters: _models.PolicyContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Creates or updates policy configuration for the API Operation level.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :param parameters: The policy contents to apply. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PolicyContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        operation_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Creates or updates policy configuration for the API Operation level.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :param parameters: The policy contents to apply. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        operation_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Creates or updates policy configuration for the API Operation level.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :param parameters: The policy contents to apply. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        operation_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        parameters: Union[_models.PolicyContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Creates or updates policy configuration for the API Operation level.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :param parameters: The policy contents to apply. Is one of the following types: PolicyContract,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PolicyContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.PolicyContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_api_operation_policy_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            api_id=api_id,
            operation_id=operation_id,
            policy_id=policy_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 200:
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if response.status_code == 201:
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PolicyContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        operation_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes the policy configuration at the Api Operation.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_api_operation_policy_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            api_id=api_id,
            operation_id=operation_id,
            policy_id=policy_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_operation(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        operation_id: str,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.PolicyContract"]:
        """Get the list of policy configuration at the API Operation level.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :return: An iterator like instance of PolicyContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.PolicyContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.PolicyContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_workspace_api_operation_policy_list_by_operation_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    workspace_id=workspace_id,
                    api_id=api_id,
                    operation_id=operation_id,
                    subscription_id=self._config.subscription_id,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.PolicyContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class WorkspaceApiPolicyOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`workspace_api_policy` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        *,
        format: Optional[Union[str, _models.PolicyExportFormat]] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Get the policy configuration at the API level.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :keyword format: Policy Export Format. Known values are: "xml" and "rawxml". Default value is
         None.
        :paramtype format: str or ~azure.mgmt.apimanagement.models.PolicyExportFormat
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.PolicyContract] = kwargs.pop("cls", None)

        _request = build_workspace_api_policy_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            api_id=api_id,
            policy_id=policy_id,
            subscription_id=self._config.subscription_id,
            format=format,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PolicyContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the API policy specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_api_policy_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            api_id=api_id,
            policy_id=policy_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        parameters: _models.PolicyContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Creates or updates policy configuration for the API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :param parameters: The policy contents to apply. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PolicyContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Creates or updates policy configuration for the API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :param parameters: The policy contents to apply. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Creates or updates policy configuration for the API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :param parameters: The policy contents to apply. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        parameters: Union[_models.PolicyContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Creates or updates policy configuration for the API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :param parameters: The policy contents to apply. Is one of the following types: PolicyContract,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PolicyContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.PolicyContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_api_policy_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            api_id=api_id,
            policy_id=policy_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 200:
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if response.status_code == 201:
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PolicyContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes the policy configuration at the Api.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_api_policy_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            api_id=api_id,
            policy_id=policy_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_api(
        self, resource_group_name: str, service_name: str, workspace_id: str, api_id: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.PolicyContract"]:
        """Get the policy configuration at the API level.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :return: An iterator like instance of PolicyContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.PolicyContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.PolicyContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_workspace_api_policy_list_by_api_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    workspace_id=workspace_id,
                    api_id=api_id,
                    subscription_id=self._config.subscription_id,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.PolicyContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class WorkspaceProductPolicyOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`workspace_product_policy` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        product_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        *,
        format: Optional[Union[str, _models.PolicyExportFormat]] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Get the policy configuration at the Product level.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :keyword format: Policy Export Format. Known values are: "xml" and "rawxml". Default value is
         None.
        :paramtype format: str or ~azure.mgmt.apimanagement.models.PolicyExportFormat
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.PolicyContract] = kwargs.pop("cls", None)

        _request = build_workspace_product_policy_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            product_id=product_id,
            policy_id=policy_id,
            subscription_id=self._config.subscription_id,
            format=format,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PolicyContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        product_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        **kwargs: Any
    ) -> bool:
        """Get the ETag of the policy configuration at the Product level.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_product_policy_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            product_id=product_id,
            policy_id=policy_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        product_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        parameters: _models.PolicyContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Creates or updates policy configuration for the Product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :param parameters: The policy contents to apply. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PolicyContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        product_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Creates or updates policy configuration for the Product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :param parameters: The policy contents to apply. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        product_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Creates or updates policy configuration for the Product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :param parameters: The policy contents to apply. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        product_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        parameters: Union[_models.PolicyContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Creates or updates policy configuration for the Product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :param parameters: The policy contents to apply. Is one of the following types: PolicyContract,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PolicyContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.PolicyContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_product_policy_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            product_id=product_id,
            policy_id=policy_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 200:
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if response.status_code == 201:
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PolicyContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        product_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes the policy configuration at the Product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_product_policy_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            product_id=product_id,
            policy_id=policy_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace_async
    async def list_by_product(
        self, resource_group_name: str, service_name: str, workspace_id: str, product_id: str, **kwargs: Any
    ) -> _models.PolicyCollection:
        """Get the policy configuration at the Product level.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :return: PolicyCollection. The PolicyCollection is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyCollection
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.PolicyCollection] = kwargs.pop("cls", None)

        _request = build_workspace_product_policy_list_by_product_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            product_id=product_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PolicyCollection, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class TagOperations:  # pylint: disable=too-many-public-methods
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`tag` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get_by_api(
        self, resource_group_name: str, service_name: str, api_id: str, tag_id: str, **kwargs: Any
    ) -> _models.TagContract:
        """Get tag associated with the API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :return: TagContract. The TagContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.TagContract] = kwargs.pop("cls", None)

        _request = build_tag_get_by_api_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            tag_id=tag_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.TagContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_state_by_api(
        self, resource_group_name: str, service_name: str, api_id: str, tag_id: str, **kwargs: Any
    ) -> bool:
        """Gets the entity state version of the tag specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_tag_get_entity_state_by_api_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            tag_id=tag_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @distributed_trace_async
    async def assign_to_api(
        self, resource_group_name: str, service_name: str, api_id: str, tag_id: str, **kwargs: Any
    ) -> _models.TagContract:
        """Assign tag to the Api.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :return: TagContract. The TagContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.TagContract] = kwargs.pop("cls", None)

        _request = build_tag_assign_to_api_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            tag_id=tag_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.TagContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def detach_from_api(
        self, resource_group_name: str, service_name: str, api_id: str, tag_id: str, **kwargs: Any
    ) -> None:
        """Detach the tag from the Api.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_tag_detach_from_api_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            tag_id=tag_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_api(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.TagContract"]:
        """Lists all Tags associated with the API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| displayName
         | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of TagContract
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.TagContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.TagContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_tag_list_by_api_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    api_id=api_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.TagContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def get_by_operation(
        self, resource_group_name: str, service_name: str, api_id: str, operation_id: str, tag_id: str, **kwargs: Any
    ) -> _models.TagContract:
        """Get tag associated with the Operation.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :return: TagContract. The TagContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.TagContract] = kwargs.pop("cls", None)

        _request = build_tag_get_by_operation_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            operation_id=operation_id,
            tag_id=tag_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.TagContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_state_by_operation(
        self, resource_group_name: str, service_name: str, api_id: str, operation_id: str, tag_id: str, **kwargs: Any
    ) -> bool:
        """Gets the entity state version of the tag specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_tag_get_entity_state_by_operation_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            operation_id=operation_id,
            tag_id=tag_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @distributed_trace_async
    async def assign_to_operation(
        self, resource_group_name: str, service_name: str, api_id: str, operation_id: str, tag_id: str, **kwargs: Any
    ) -> _models.TagContract:
        """Assign tag to the Operation.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :return: TagContract. The TagContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.TagContract] = kwargs.pop("cls", None)

        _request = build_tag_assign_to_operation_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            operation_id=operation_id,
            tag_id=tag_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.TagContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def detach_from_operation(
        self, resource_group_name: str, service_name: str, api_id: str, operation_id: str, tag_id: str, **kwargs: Any
    ) -> None:
        """Detach the tag from the Operation.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_tag_detach_from_operation_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            operation_id=operation_id,
            tag_id=tag_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_operation(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        operation_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.TagContract"]:
        """Lists all Tags associated with the Operation.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| displayName
         | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of TagContract
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.TagContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.TagContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_tag_list_by_operation_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    api_id=api_id,
                    operation_id=operation_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.TagContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def get_by_product(
        self, resource_group_name: str, service_name: str, product_id: str, tag_id: str, **kwargs: Any
    ) -> _models.TagContract:
        """Get tag associated with the Product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :return: TagContract. The TagContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.TagContract] = kwargs.pop("cls", None)

        _request = build_tag_get_by_product_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            product_id=product_id,
            tag_id=tag_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.TagContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_state_by_product(
        self, resource_group_name: str, service_name: str, product_id: str, tag_id: str, **kwargs: Any
    ) -> bool:
        """Gets the entity state version of the tag specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_tag_get_entity_state_by_product_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            product_id=product_id,
            tag_id=tag_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @distributed_trace_async
    async def assign_to_product(
        self, resource_group_name: str, service_name: str, product_id: str, tag_id: str, **kwargs: Any
    ) -> _models.TagContract:
        """Assign tag to the Product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :return: TagContract. The TagContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.TagContract] = kwargs.pop("cls", None)

        _request = build_tag_assign_to_product_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            product_id=product_id,
            tag_id=tag_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.TagContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def detach_from_product(
        self, resource_group_name: str, service_name: str, product_id: str, tag_id: str, **kwargs: Any
    ) -> None:
        """Detach the tag from the Product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_tag_detach_from_product_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            product_id=product_id,
            tag_id=tag_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_product(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.TagContract"]:
        """Lists all Tags associated with the Product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| displayName
         | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of TagContract
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.TagContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.TagContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_tag_list_by_product_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    product_id=product_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.TagContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def get(self, resource_group_name: str, service_name: str, tag_id: str, **kwargs: Any) -> _models.TagContract:
        """Gets the details of the tag specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :return: TagContract. The TagContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.TagContract] = kwargs.pop("cls", None)

        _request = build_tag_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            tag_id=tag_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.TagContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_state(self, resource_group_name: str, service_name: str, tag_id: str, **kwargs: Any) -> bool:
        """Gets the entity state version of the tag specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_tag_get_entity_state_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            tag_id=tag_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        tag_id: str,
        parameters: _models.TagCreateUpdateParameters,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.TagContract:
        """Creates a tag.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.TagCreateUpdateParameters
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: TagContract. The TagContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        tag_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.TagContract:
        """Creates a tag.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: TagContract. The TagContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        tag_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.TagContract:
        """Creates a tag.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: TagContract. The TagContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        tag_id: str,
        parameters: Union[_models.TagCreateUpdateParameters, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.TagContract:
        """Creates a tag.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param parameters: Create parameters. Is one of the following types: TagCreateUpdateParameters,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.TagCreateUpdateParameters or JSON or
         IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: TagContract. The TagContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.TagContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_tag_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            tag_id=tag_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.TagContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        tag_id: str,
        parameters: _models.TagCreateUpdateParameters,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.TagContract:
        """Updates the details of the tag specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param parameters: Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.TagCreateUpdateParameters
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: TagContract. The TagContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        tag_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.TagContract:
        """Updates the details of the tag specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param parameters: Update parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: TagContract. The TagContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        tag_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.TagContract:
        """Updates the details of the tag specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param parameters: Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: TagContract. The TagContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        tag_id: str,
        parameters: Union[_models.TagCreateUpdateParameters, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.TagContract:
        """Updates the details of the tag specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param parameters: Update parameters. Is one of the following types: TagCreateUpdateParameters,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.TagCreateUpdateParameters or JSON or
         IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: TagContract. The TagContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.TagContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_tag_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            tag_id=tag_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.TagContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        tag_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes specific tag of the API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_tag_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            tag_id=tag_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        scope: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.TagContract"]:
        """Lists a collection of tags defined within a service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         displayName | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :keyword scope: Scope like 'apis', 'products' or 'apis/{apiId}. Default value is None.
        :paramtype scope: str
        :return: An iterator like instance of TagContract
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.TagContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.TagContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_tag_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    scope=scope,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.TagContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class WorkspaceTagOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`workspace_tag` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, workspace_id: str, tag_id: str, **kwargs: Any
    ) -> _models.TagContract:
        """Gets the details of the tag specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :return: TagContract. The TagContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.TagContract] = kwargs.pop("cls", None)

        _request = build_workspace_tag_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            tag_id=tag_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.TagContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_state(
        self, resource_group_name: str, service_name: str, workspace_id: str, tag_id: str, **kwargs: Any
    ) -> bool:
        """Gets the entity state version of the tag specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_tag_get_entity_state_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            tag_id=tag_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        tag_id: str,
        parameters: _models.TagCreateUpdateParameters,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.TagContract:
        """Creates a tag.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.TagCreateUpdateParameters
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: TagContract. The TagContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        tag_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.TagContract:
        """Creates a tag.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: TagContract. The TagContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        tag_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.TagContract:
        """Creates a tag.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: TagContract. The TagContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        tag_id: str,
        parameters: Union[_models.TagCreateUpdateParameters, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.TagContract:
        """Creates a tag.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param parameters: Create parameters. Is one of the following types: TagCreateUpdateParameters,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.TagCreateUpdateParameters or JSON or
         IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: TagContract. The TagContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.TagContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_tag_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            tag_id=tag_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.TagContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        tag_id: str,
        parameters: _models.TagCreateUpdateParameters,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.TagContract:
        """Updates the details of the tag specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param parameters: Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.TagCreateUpdateParameters
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: TagContract. The TagContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        tag_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.TagContract:
        """Updates the details of the tag specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param parameters: Update parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: TagContract. The TagContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        tag_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.TagContract:
        """Updates the details of the tag specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param parameters: Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: TagContract. The TagContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        tag_id: str,
        parameters: Union[_models.TagCreateUpdateParameters, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.TagContract:
        """Updates the details of the tag specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param parameters: Update parameters. Is one of the following types: TagCreateUpdateParameters,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.TagCreateUpdateParameters or JSON or
         IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: TagContract. The TagContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.TagContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_tag_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            tag_id=tag_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.TagContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        tag_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes specific tag of the workspace in an API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_tag_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            tag_id=tag_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        scope: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.TagContract"]:
        """Lists a collection of tags defined within a workspace in a service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         displayName | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :keyword scope: Scope like 'apis', 'products' or 'apis/{apiId}. Default value is None.
        :paramtype scope: str
        :return: An iterator like instance of TagContract
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.TagContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.TagContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_workspace_tag_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    workspace_id=workspace_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    scope=scope,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.TagContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class WorkspaceApiSchemaOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`workspace_api_schema` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, workspace_id: str, api_id: str, schema_id: str, **kwargs: Any
    ) -> _models.SchemaContract:
        """Get the schema configuration at the API level.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param schema_id: Schema id identifier. Must be unique in the current API Management service
         instance. Required.
        :type schema_id: str
        :return: SchemaContract. The SchemaContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.SchemaContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.SchemaContract] = kwargs.pop("cls", None)

        _request = build_workspace_api_schema_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            api_id=api_id,
            schema_id=schema_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.SchemaContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, workspace_id: str, api_id: str, schema_id: str, **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the schema specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param schema_id: Schema id identifier. Must be unique in the current API Management service
         instance. Required.
        :type schema_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_api_schema_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            api_id=api_id,
            schema_id=schema_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    async def _create_or_update_initial(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        schema_id: str,
        parameters: Union[_models.SchemaContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_api_schema_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            api_id=api_id,
            schema_id=schema_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 200:
            response_headers["Azure-AsyncOperation"] = self._deserialize(
                "str", response.headers.get("Azure-AsyncOperation")
            )
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if response.status_code == 201:
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))
            response_headers["Azure-AsyncOperation"] = self._deserialize(
                "str", response.headers.get("Azure-AsyncOperation")
            )
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        schema_id: str,
        parameters: _models.SchemaContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.SchemaContract]:
        """Creates or updates schema configuration for the API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param schema_id: Schema id identifier. Must be unique in the current API Management service
         instance. Required.
        :type schema_id: str
        :param parameters: The schema contents to apply. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.SchemaContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns SchemaContract. The SchemaContract is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.SchemaContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        schema_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.SchemaContract]:
        """Creates or updates schema configuration for the API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param schema_id: Schema id identifier. Must be unique in the current API Management service
         instance. Required.
        :type schema_id: str
        :param parameters: The schema contents to apply. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns SchemaContract. The SchemaContract is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.SchemaContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        schema_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.SchemaContract]:
        """Creates or updates schema configuration for the API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param schema_id: Schema id identifier. Must be unique in the current API Management service
         instance. Required.
        :type schema_id: str
        :param parameters: The schema contents to apply. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns SchemaContract. The SchemaContract is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.SchemaContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        schema_id: str,
        parameters: Union[_models.SchemaContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.SchemaContract]:
        """Creates or updates schema configuration for the API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param schema_id: Schema id identifier. Must be unique in the current API Management service
         instance. Required.
        :type schema_id: str
        :param parameters: The schema contents to apply. Is one of the following types: SchemaContract,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.SchemaContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns SchemaContract. The SchemaContract is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.SchemaContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.SchemaContract] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._create_or_update_initial(
                resource_group_name=resource_group_name,
                service_name=service_name,
                workspace_id=workspace_id,
                api_id=api_id,
                schema_id=schema_id,
                parameters=parameters,
                etag=etag,
                match_condition=match_condition,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response_headers = {}
            response = pipeline_response.http_response
            response_headers["Azure-AsyncOperation"] = self._deserialize(
                "str", response.headers.get("Azure-AsyncOperation")
            )
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

            deserialized = _deserialize(_models.SchemaContract, response.json())
            if cls:
                return cls(pipeline_response, deserialized, response_headers)  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.SchemaContract].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.SchemaContract](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        schema_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        force: Optional[bool] = None,
        **kwargs: Any
    ) -> None:
        """Deletes the schema configuration at the Api.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param schema_id: Schema id identifier. Must be unique in the current API Management service
         instance. Required.
        :type schema_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword force: If true removes all references to the schema before deleting it. Default value
         is None.
        :paramtype force: bool
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_api_schema_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            api_id=api_id,
            schema_id=schema_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            force=force,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_api(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.SchemaContract"]:
        """Get the schema configuration at the API level.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| contentType
         | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of SchemaContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.SchemaContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.SchemaContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_workspace_api_schema_list_by_api_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    workspace_id=workspace_id,
                    api_id=api_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.SchemaContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class DiagnosticOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`diagnostic` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, diagnostic_id: str, **kwargs: Any
    ) -> _models.DiagnosticContract:
        """Gets the details of the Diagnostic specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :return: DiagnosticContract. The DiagnosticContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.DiagnosticContract] = kwargs.pop("cls", None)

        _request = build_diagnostic_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            diagnostic_id=diagnostic_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.DiagnosticContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, diagnostic_id: str, **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the Diagnostic specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_diagnostic_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            diagnostic_id=diagnostic_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        diagnostic_id: str,
        parameters: _models.DiagnosticContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.DiagnosticContract:
        """Creates a new Diagnostic or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: DiagnosticContract. The DiagnosticContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        diagnostic_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.DiagnosticContract:
        """Creates a new Diagnostic or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: DiagnosticContract. The DiagnosticContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        diagnostic_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.DiagnosticContract:
        """Creates a new Diagnostic or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: DiagnosticContract. The DiagnosticContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        diagnostic_id: str,
        parameters: Union[_models.DiagnosticContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.DiagnosticContract:
        """Creates a new Diagnostic or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :param parameters: Create parameters. Is one of the following types: DiagnosticContract, JSON,
         IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.DiagnosticContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: DiagnosticContract. The DiagnosticContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.DiagnosticContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_diagnostic_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            diagnostic_id=diagnostic_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 200:
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if response.status_code == 201:
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.DiagnosticContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        diagnostic_id: str,
        parameters: _models.DiagnosticContract,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.DiagnosticContract:
        """Updates the details of the Diagnostic specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :param parameters: Diagnostic Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: DiagnosticContract. The DiagnosticContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        diagnostic_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.DiagnosticContract:
        """Updates the details of the Diagnostic specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :param parameters: Diagnostic Update parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: DiagnosticContract. The DiagnosticContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        diagnostic_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.DiagnosticContract:
        """Updates the details of the Diagnostic specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :param parameters: Diagnostic Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: DiagnosticContract. The DiagnosticContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        diagnostic_id: str,
        parameters: Union[_models.DiagnosticContract, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.DiagnosticContract:
        """Updates the details of the Diagnostic specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :param parameters: Diagnostic Update parameters. Is one of the following types:
         DiagnosticContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.DiagnosticContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: DiagnosticContract. The DiagnosticContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.DiagnosticContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_diagnostic_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            diagnostic_id=diagnostic_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.DiagnosticContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        diagnostic_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes the specified Diagnostic.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_diagnostic_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            diagnostic_id=diagnostic_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.DiagnosticContract"]:
        """Lists all diagnostics of the API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of DiagnosticContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.DiagnosticContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.DiagnosticContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_diagnostic_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.DiagnosticContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class WorkspaceDiagnosticOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`workspace_diagnostic` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, workspace_id: str, diagnostic_id: str, **kwargs: Any
    ) -> _models.DiagnosticContract:
        """Gets the details of the Diagnostic specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :return: DiagnosticContract. The DiagnosticContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.DiagnosticContract] = kwargs.pop("cls", None)

        _request = build_workspace_diagnostic_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            diagnostic_id=diagnostic_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.DiagnosticContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, workspace_id: str, diagnostic_id: str, **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the Diagnostic specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_diagnostic_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            diagnostic_id=diagnostic_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        diagnostic_id: str,
        parameters: _models.DiagnosticContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.DiagnosticContract:
        """Creates a new Diagnostic or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: DiagnosticContract. The DiagnosticContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        diagnostic_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.DiagnosticContract:
        """Creates a new Diagnostic or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: DiagnosticContract. The DiagnosticContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        diagnostic_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.DiagnosticContract:
        """Creates a new Diagnostic or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: DiagnosticContract. The DiagnosticContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        diagnostic_id: str,
        parameters: Union[_models.DiagnosticContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.DiagnosticContract:
        """Creates a new Diagnostic or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :param parameters: Create parameters. Is one of the following types: DiagnosticContract, JSON,
         IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.DiagnosticContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: DiagnosticContract. The DiagnosticContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.DiagnosticContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_diagnostic_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            diagnostic_id=diagnostic_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 200:
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if response.status_code == 201:
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.DiagnosticContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        diagnostic_id: str,
        parameters: _models.DiagnosticUpdateContract,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.DiagnosticContract:
        """Updates the details of the Diagnostic specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :param parameters: Diagnostic Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.DiagnosticUpdateContract
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: DiagnosticContract. The DiagnosticContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        diagnostic_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.DiagnosticContract:
        """Updates the details of the Diagnostic specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :param parameters: Diagnostic Update parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: DiagnosticContract. The DiagnosticContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        diagnostic_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.DiagnosticContract:
        """Updates the details of the Diagnostic specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :param parameters: Diagnostic Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: DiagnosticContract. The DiagnosticContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        diagnostic_id: str,
        parameters: Union[_models.DiagnosticUpdateContract, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.DiagnosticContract:
        """Updates the details of the Diagnostic specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :param parameters: Diagnostic Update parameters. Is one of the following types:
         DiagnosticUpdateContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.DiagnosticUpdateContract or JSON or
         IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: DiagnosticContract. The DiagnosticContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.DiagnosticContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_diagnostic_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            diagnostic_id=diagnostic_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.DiagnosticContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        diagnostic_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes the specified Diagnostic.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_diagnostic_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            diagnostic_id=diagnostic_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_workspace(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.DiagnosticContract"]:
        """Lists all diagnostics in the specified workspace.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of DiagnosticContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.DiagnosticContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.DiagnosticContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_workspace_diagnostic_list_by_workspace_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    workspace_id=workspace_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.DiagnosticContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class WorkspaceApiDiagnosticOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`workspace_api_diagnostic` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        diagnostic_id: str,
        **kwargs: Any
    ) -> _models.DiagnosticContract:
        """Gets the details of the Diagnostic for an API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :return: DiagnosticContract. The DiagnosticContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.DiagnosticContract] = kwargs.pop("cls", None)

        _request = build_workspace_api_diagnostic_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            api_id=api_id,
            diagnostic_id=diagnostic_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.DiagnosticContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        diagnostic_id: str,
        **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the Diagnostic for an API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_api_diagnostic_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            api_id=api_id,
            diagnostic_id=diagnostic_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        diagnostic_id: str,
        parameters: _models.DiagnosticContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.DiagnosticContract:
        """Creates a new Diagnostic for an API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: DiagnosticContract. The DiagnosticContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        diagnostic_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.DiagnosticContract:
        """Creates a new Diagnostic for an API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: DiagnosticContract. The DiagnosticContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        diagnostic_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.DiagnosticContract:
        """Creates a new Diagnostic for an API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: DiagnosticContract. The DiagnosticContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        diagnostic_id: str,
        parameters: Union[_models.DiagnosticContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.DiagnosticContract:
        """Creates a new Diagnostic for an API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :param parameters: Create parameters. Is one of the following types: DiagnosticContract, JSON,
         IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.DiagnosticContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: DiagnosticContract. The DiagnosticContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.DiagnosticContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_api_diagnostic_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            api_id=api_id,
            diagnostic_id=diagnostic_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 200:
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if response.status_code == 201:
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.DiagnosticContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        diagnostic_id: str,
        parameters: _models.DiagnosticUpdateContract,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.DiagnosticContract:
        """Updates the details of the Diagnostic for an API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :param parameters: Diagnostic Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.DiagnosticUpdateContract
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: DiagnosticContract. The DiagnosticContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        diagnostic_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.DiagnosticContract:
        """Updates the details of the Diagnostic for an API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :param parameters: Diagnostic Update parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: DiagnosticContract. The DiagnosticContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        diagnostic_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.DiagnosticContract:
        """Updates the details of the Diagnostic for an API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :param parameters: Diagnostic Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: DiagnosticContract. The DiagnosticContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        diagnostic_id: str,
        parameters: Union[_models.DiagnosticUpdateContract, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.DiagnosticContract:
        """Updates the details of the Diagnostic for an API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :param parameters: Diagnostic Update parameters. Is one of the following types:
         DiagnosticUpdateContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.DiagnosticUpdateContract or JSON or
         IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: DiagnosticContract. The DiagnosticContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.DiagnosticContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_api_diagnostic_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            api_id=api_id,
            diagnostic_id=diagnostic_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.DiagnosticContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        diagnostic_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes the specified Diagnostic from an API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_api_diagnostic_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            api_id=api_id,
            diagnostic_id=diagnostic_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_workspace(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.DiagnosticContract"]:
        """Lists all diagnostics of an API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of DiagnosticContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.DiagnosticContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.DiagnosticContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_workspace_api_diagnostic_list_by_workspace_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    workspace_id=workspace_id,
                    api_id=api_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.DiagnosticContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class IssueOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`issue` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, issue_id: str, **kwargs: Any
    ) -> _models.IssueContract:
        """Gets API Management issue details.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param issue_id: Issue identifier. Must be unique in the current API Management service
         instance. Required.
        :type issue_id: str
        :return: IssueContract. The IssueContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.IssueContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.IssueContract] = kwargs.pop("cls", None)

        _request = build_issue_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            issue_id=issue_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.IssueContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.IssueContract"]:
        """Lists a collection of issues in the specified service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>| apiId |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>| title |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         description | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>| authorName | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
         endswith |</br>| state | filter | eq |     |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of IssueContract
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.IssueContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.IssueContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_issue_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.IssueContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class ProductWikiOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`product_wiki` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, product_id: str, **kwargs: Any
    ) -> _models.WikiContract:
        """Gets the details of the Wiki for a Product specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :return: WikiContract. The WikiContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.WikiContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.WikiContract] = kwargs.pop("cls", None)

        _request = build_product_wiki_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            product_id=product_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.WikiContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(self, resource_group_name: str, service_name: str, product_id: str, **kwargs: Any) -> bool:
        """Gets the entity state (Etag) version of the Wiki for a Product specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_product_wiki_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            product_id=product_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        parameters: _models.WikiContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.WikiContract:
        """Creates a new Wiki for a Product or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.WikiContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: WikiContract. The WikiContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.WikiContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.WikiContract:
        """Creates a new Wiki for a Product or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: WikiContract. The WikiContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.WikiContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.WikiContract:
        """Creates a new Wiki for a Product or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: WikiContract. The WikiContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.WikiContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        parameters: Union[_models.WikiContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.WikiContract:
        """Creates a new Wiki for a Product or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param parameters: Create parameters. Is one of the following types: WikiContract, JSON,
         IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.WikiContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: WikiContract. The WikiContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.WikiContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.WikiContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_product_wiki_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            product_id=product_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 200:
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if response.status_code == 201:
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.WikiContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        parameters: _models.WikiUpdateContract,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.WikiContract:
        """Updates the details of the Wiki for a Product specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param parameters: Wiki Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.WikiUpdateContract
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: WikiContract. The WikiContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.WikiContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.WikiContract:
        """Updates the details of the Wiki for a Product specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param parameters: Wiki Update parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: WikiContract. The WikiContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.WikiContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.WikiContract:
        """Updates the details of the Wiki for a Product specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param parameters: Wiki Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: WikiContract. The WikiContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.WikiContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        parameters: Union[_models.WikiUpdateContract, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.WikiContract:
        """Updates the details of the Wiki for a Product specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param parameters: Wiki Update parameters. Is one of the following types: WikiUpdateContract,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.WikiUpdateContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: WikiContract. The WikiContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.WikiContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.WikiContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_product_wiki_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            product_id=product_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.WikiContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes the specified Wiki from a Product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_product_wiki_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            product_id=product_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore


class WorkspaceApiVersionSetOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`workspace_api_version_set` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, workspace_id: str, version_set_id: str, **kwargs: Any
    ) -> _models.ApiVersionSetContract:
        """Gets the details of the Api Version Set specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param version_set_id: Api Version Set identifier. Must be unique in the current API Management
         service instance. Required.
        :type version_set_id: str
        :return: ApiVersionSetContract. The ApiVersionSetContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiVersionSetContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ApiVersionSetContract] = kwargs.pop("cls", None)

        _request = build_workspace_api_version_set_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            version_set_id=version_set_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ApiVersionSetContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, workspace_id: str, version_set_id: str, **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the Api Version Set specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param version_set_id: Api Version Set identifier. Must be unique in the current API Management
         service instance. Required.
        :type version_set_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_api_version_set_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            version_set_id=version_set_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        version_set_id: str,
        parameters: _models.ApiVersionSetContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ApiVersionSetContract:
        """Creates or Updates a Api Version Set.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param version_set_id: Api Version Set identifier. Must be unique in the current API Management
         service instance. Required.
        :type version_set_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiVersionSetContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ApiVersionSetContract. The ApiVersionSetContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiVersionSetContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        version_set_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ApiVersionSetContract:
        """Creates or Updates a Api Version Set.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param version_set_id: Api Version Set identifier. Must be unique in the current API Management
         service instance. Required.
        :type version_set_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ApiVersionSetContract. The ApiVersionSetContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiVersionSetContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        version_set_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ApiVersionSetContract:
        """Creates or Updates a Api Version Set.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param version_set_id: Api Version Set identifier. Must be unique in the current API Management
         service instance. Required.
        :type version_set_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ApiVersionSetContract. The ApiVersionSetContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiVersionSetContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        version_set_id: str,
        parameters: Union[_models.ApiVersionSetContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ApiVersionSetContract:
        """Creates or Updates a Api Version Set.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param version_set_id: Api Version Set identifier. Must be unique in the current API Management
         service instance. Required.
        :type version_set_id: str
        :param parameters: Create or update parameters. Is one of the following types:
         ApiVersionSetContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiVersionSetContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ApiVersionSetContract. The ApiVersionSetContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiVersionSetContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ApiVersionSetContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_api_version_set_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            version_set_id=version_set_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ApiVersionSetContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        version_set_id: str,
        parameters: _models.ApiVersionSetUpdateParameters,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ApiVersionSetContract:
        """Updates the details of the Api VersionSet specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param version_set_id: Api Version Set identifier. Must be unique in the current API Management
         service instance. Required.
        :type version_set_id: str
        :param parameters: Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiVersionSetUpdateParameters
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ApiVersionSetContract. The ApiVersionSetContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiVersionSetContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        version_set_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ApiVersionSetContract:
        """Updates the details of the Api VersionSet specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param version_set_id: Api Version Set identifier. Must be unique in the current API Management
         service instance. Required.
        :type version_set_id: str
        :param parameters: Update parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ApiVersionSetContract. The ApiVersionSetContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiVersionSetContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        version_set_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ApiVersionSetContract:
        """Updates the details of the Api VersionSet specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param version_set_id: Api Version Set identifier. Must be unique in the current API Management
         service instance. Required.
        :type version_set_id: str
        :param parameters: Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ApiVersionSetContract. The ApiVersionSetContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiVersionSetContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        version_set_id: str,
        parameters: Union[_models.ApiVersionSetUpdateParameters, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.ApiVersionSetContract:
        """Updates the details of the Api VersionSet specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param version_set_id: Api Version Set identifier. Must be unique in the current API Management
         service instance. Required.
        :type version_set_id: str
        :param parameters: Update parameters. Is one of the following types:
         ApiVersionSetUpdateParameters, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiVersionSetUpdateParameters or JSON or
         IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ApiVersionSetContract. The ApiVersionSetContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiVersionSetContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ApiVersionSetContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_api_version_set_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            version_set_id=version_set_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ApiVersionSetContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        version_set_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes specific Api Version Set.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param version_set_id: Api Version Set identifier. Must be unique in the current API Management
         service instance. Required.
        :type version_set_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_api_version_set_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            version_set_id=version_set_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.ApiVersionSetContract"]:
        """Lists a collection of API Version Sets in the specified workspace with a service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of ApiVersionSetContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ApiVersionSetContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ApiVersionSetContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_workspace_api_version_set_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    workspace_id=workspace_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ApiVersionSetContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class WorkspaceBackendOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`workspace_backend` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, workspace_id: str, backend_id: str, **kwargs: Any
    ) -> _models.BackendContract:
        """Gets the details of the backend specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param backend_id: Identifier of the Backend entity. Must be unique in the current API
         Management service instance. Required.
        :type backend_id: str
        :return: BackendContract. The BackendContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.BackendContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.BackendContract] = kwargs.pop("cls", None)

        _request = build_workspace_backend_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            backend_id=backend_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.BackendContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, workspace_id: str, backend_id: str, **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the backend specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param backend_id: Identifier of the Backend entity. Must be unique in the current API
         Management service instance. Required.
        :type backend_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_backend_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            backend_id=backend_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        backend_id: str,
        parameters: _models.BackendContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.BackendContract:
        """Creates or Updates a backend.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param backend_id: Identifier of the Backend entity. Must be unique in the current API
         Management service instance. Required.
        :type backend_id: str
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.BackendContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: BackendContract. The BackendContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.BackendContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        backend_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.BackendContract:
        """Creates or Updates a backend.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param backend_id: Identifier of the Backend entity. Must be unique in the current API
         Management service instance. Required.
        :type backend_id: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: BackendContract. The BackendContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.BackendContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        backend_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.BackendContract:
        """Creates or Updates a backend.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param backend_id: Identifier of the Backend entity. Must be unique in the current API
         Management service instance. Required.
        :type backend_id: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: BackendContract. The BackendContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.BackendContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        backend_id: str,
        parameters: Union[_models.BackendContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.BackendContract:
        """Creates or Updates a backend.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param backend_id: Identifier of the Backend entity. Must be unique in the current API
         Management service instance. Required.
        :type backend_id: str
        :param parameters: Create parameters. Is one of the following types: BackendContract, JSON,
         IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.BackendContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: BackendContract. The BackendContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.BackendContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.BackendContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_backend_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            backend_id=backend_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 200:
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if response.status_code == 201:
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.BackendContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        backend_id: str,
        parameters: _models.BackendUpdateParameters,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.BackendContract:
        """Updates an existing backend.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param backend_id: Identifier of the Backend entity. Must be unique in the current API
         Management service instance. Required.
        :type backend_id: str
        :param parameters: Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.BackendUpdateParameters
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: BackendContract. The BackendContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.BackendContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        backend_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.BackendContract:
        """Updates an existing backend.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param backend_id: Identifier of the Backend entity. Must be unique in the current API
         Management service instance. Required.
        :type backend_id: str
        :param parameters: Update parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: BackendContract. The BackendContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.BackendContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        backend_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.BackendContract:
        """Updates an existing backend.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param backend_id: Identifier of the Backend entity. Must be unique in the current API
         Management service instance. Required.
        :type backend_id: str
        :param parameters: Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: BackendContract. The BackendContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.BackendContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        backend_id: str,
        parameters: Union[_models.BackendUpdateParameters, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.BackendContract:
        """Updates an existing backend.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param backend_id: Identifier of the Backend entity. Must be unique in the current API
         Management service instance. Required.
        :type backend_id: str
        :param parameters: Update parameters. Is one of the following types: BackendUpdateParameters,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.BackendUpdateParameters or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: BackendContract. The BackendContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.BackendContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.BackendContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_backend_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            backend_id=backend_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.BackendContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        backend_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes the specified backend.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param backend_id: Identifier of the Backend entity. Must be unique in the current API
         Management service instance. Required.
        :type backend_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_backend_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            backend_id=backend_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_workspace(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.BackendContract"]:
        """Lists a collection of backends in the specified workspace.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>| title |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>| url |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of BackendContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.BackendContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BackendContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_workspace_backend_list_by_workspace_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    workspace_id=workspace_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BackendContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class WorkspaceCertificateOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`workspace_certificate` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, workspace_id: str, certificate_id: str, **kwargs: Any
    ) -> _models.CertificateContract:
        """Gets the details of the certificate specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param certificate_id: Identifier of the certificate entity. Must be unique in the current API
         Management service instance. Required.
        :type certificate_id: str
        :return: CertificateContract. The CertificateContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.CertificateContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.CertificateContract] = kwargs.pop("cls", None)

        _request = build_workspace_certificate_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            certificate_id=certificate_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.CertificateContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, workspace_id: str, certificate_id: str, **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the certificate specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param certificate_id: Identifier of the certificate entity. Must be unique in the current API
         Management service instance. Required.
        :type certificate_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_certificate_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            certificate_id=certificate_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        certificate_id: str,
        parameters: _models.CertificateCreateOrUpdateParameters,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.CertificateContract:
        """Creates or updates the certificate being used for authentication with the backend.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param certificate_id: Identifier of the certificate entity. Must be unique in the current API
         Management service instance. Required.
        :type certificate_id: str
        :param parameters: Create or Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.CertificateCreateOrUpdateParameters
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: CertificateContract. The CertificateContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.CertificateContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        certificate_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.CertificateContract:
        """Creates or updates the certificate being used for authentication with the backend.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param certificate_id: Identifier of the certificate entity. Must be unique in the current API
         Management service instance. Required.
        :type certificate_id: str
        :param parameters: Create or Update parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: CertificateContract. The CertificateContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.CertificateContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        certificate_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.CertificateContract:
        """Creates or updates the certificate being used for authentication with the backend.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param certificate_id: Identifier of the certificate entity. Must be unique in the current API
         Management service instance. Required.
        :type certificate_id: str
        :param parameters: Create or Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: CertificateContract. The CertificateContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.CertificateContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        certificate_id: str,
        parameters: Union[_models.CertificateCreateOrUpdateParameters, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.CertificateContract:
        """Creates or updates the certificate being used for authentication with the backend.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param certificate_id: Identifier of the certificate entity. Must be unique in the current API
         Management service instance. Required.
        :type certificate_id: str
        :param parameters: Create or Update parameters. Is one of the following types:
         CertificateCreateOrUpdateParameters, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.CertificateCreateOrUpdateParameters or JSON
         or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: CertificateContract. The CertificateContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.CertificateContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.CertificateContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_certificate_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            certificate_id=certificate_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.CertificateContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        certificate_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes specific certificate.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param certificate_id: Identifier of the certificate entity. Must be unique in the current API
         Management service instance. Required.
        :type certificate_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_certificate_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            certificate_id=certificate_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_workspace(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        is_key_vault_refresh_failed: Optional[bool] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.CertificateContract"]:
        """Lists a collection of all certificates in the specified workspace.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>| subject |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         thumbprint | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>| expirationDate | filter | ge, le, eq, ne, gt, lt |     |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :keyword is_key_vault_refresh_failed: When set to true, the response contains only certificates
         entities which failed refresh. Default value is None.
        :paramtype is_key_vault_refresh_failed: bool
        :return: An iterator like instance of CertificateContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.CertificateContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.CertificateContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_workspace_certificate_list_by_workspace_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    workspace_id=workspace_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    is_key_vault_refresh_failed=is_key_vault_refresh_failed,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.CertificateContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def refresh_secret(
        self, resource_group_name: str, service_name: str, workspace_id: str, certificate_id: str, **kwargs: Any
    ) -> _models.CertificateContract:
        """From KeyVault, Refresh the certificate being used for authentication with the backend.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param certificate_id: Identifier of the certificate entity. Must be unique in the current API
         Management service instance. Required.
        :type certificate_id: str
        :return: CertificateContract. The CertificateContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.CertificateContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.CertificateContract] = kwargs.pop("cls", None)

        _request = build_workspace_certificate_refresh_secret_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            certificate_id=certificate_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.CertificateContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore


class WorkspaceGroupOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`workspace_group` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, workspace_id: str, group_id: str, **kwargs: Any
    ) -> _models.GroupContract:
        """Gets the details of the group specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param group_id: Group identifier. Must be unique in the current API Management service
         instance. Required.
        :type group_id: str
        :return: GroupContract. The GroupContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GroupContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.GroupContract] = kwargs.pop("cls", None)

        _request = build_workspace_group_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            group_id=group_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.GroupContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, workspace_id: str, group_id: str, **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the group specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param group_id: Group identifier. Must be unique in the current API Management service
         instance. Required.
        :type group_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_group_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            group_id=group_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        group_id: str,
        parameters: _models.GroupCreateParameters,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.GroupContract:
        """Creates or Updates a group.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param group_id: Group identifier. Must be unique in the current API Management service
         instance. Required.
        :type group_id: str
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.GroupCreateParameters
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: GroupContract. The GroupContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GroupContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        group_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.GroupContract:
        """Creates or Updates a group.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param group_id: Group identifier. Must be unique in the current API Management service
         instance. Required.
        :type group_id: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: GroupContract. The GroupContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GroupContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        group_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.GroupContract:
        """Creates or Updates a group.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param group_id: Group identifier. Must be unique in the current API Management service
         instance. Required.
        :type group_id: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: GroupContract. The GroupContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GroupContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        group_id: str,
        parameters: Union[_models.GroupCreateParameters, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.GroupContract:
        """Creates or Updates a group.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param group_id: Group identifier. Must be unique in the current API Management service
         instance. Required.
        :type group_id: str
        :param parameters: Create parameters. Is one of the following types: GroupCreateParameters,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.GroupCreateParameters or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: GroupContract. The GroupContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GroupContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.GroupContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_group_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            group_id=group_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.GroupContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        group_id: str,
        parameters: _models.GroupUpdateParameters,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.GroupContract:
        """Updates the details of the group specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param group_id: Group identifier. Must be unique in the current API Management service
         instance. Required.
        :type group_id: str
        :param parameters: Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.GroupUpdateParameters
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: GroupContract. The GroupContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GroupContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        group_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.GroupContract:
        """Updates the details of the group specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param group_id: Group identifier. Must be unique in the current API Management service
         instance. Required.
        :type group_id: str
        :param parameters: Update parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: GroupContract. The GroupContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GroupContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        group_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.GroupContract:
        """Updates the details of the group specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param group_id: Group identifier. Must be unique in the current API Management service
         instance. Required.
        :type group_id: str
        :param parameters: Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: GroupContract. The GroupContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GroupContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        group_id: str,
        parameters: Union[_models.GroupUpdateParameters, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.GroupContract:
        """Updates the details of the group specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param group_id: Group identifier. Must be unique in the current API Management service
         instance. Required.
        :type group_id: str
        :param parameters: Update parameters. Is one of the following types: GroupUpdateParameters,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.GroupUpdateParameters or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: GroupContract. The GroupContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GroupContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.GroupContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_group_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            group_id=group_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.GroupContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        group_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes specific group of the workspace in an API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param group_id: Group identifier. Must be unique in the current API Management service
         instance. Required.
        :type group_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_group_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            group_id=group_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.GroupContract"]:
        """Lists a collection of groups defined within a workspace in a service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         displayName | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>| description | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
         endswith |</br>| externalId | filter | eq |     |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of GroupContract
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.GroupContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.GroupContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_workspace_group_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    workspace_id=workspace_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.GroupContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class WorkspaceLoggerOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`workspace_logger` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, workspace_id: str, logger_id: str, **kwargs: Any
    ) -> _models.LoggerContract:
        """Gets the details of the logger specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param logger_id: Logger identifier. Must be unique in the API Management service instance.
         Required.
        :type logger_id: str
        :return: LoggerContract. The LoggerContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.LoggerContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.LoggerContract] = kwargs.pop("cls", None)

        _request = build_workspace_logger_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            logger_id=logger_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.LoggerContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, workspace_id: str, logger_id: str, **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the logger specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param logger_id: Logger identifier. Must be unique in the API Management service instance.
         Required.
        :type logger_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_logger_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            logger_id=logger_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        logger_id: str,
        parameters: _models.LoggerContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.LoggerContract:
        """Creates or Updates a logger.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param logger_id: Logger identifier. Must be unique in the API Management service instance.
         Required.
        :type logger_id: str
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.LoggerContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: LoggerContract. The LoggerContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.LoggerContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        logger_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.LoggerContract:
        """Creates or Updates a logger.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param logger_id: Logger identifier. Must be unique in the API Management service instance.
         Required.
        :type logger_id: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: LoggerContract. The LoggerContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.LoggerContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        logger_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.LoggerContract:
        """Creates or Updates a logger.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param logger_id: Logger identifier. Must be unique in the API Management service instance.
         Required.
        :type logger_id: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: LoggerContract. The LoggerContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.LoggerContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        logger_id: str,
        parameters: Union[_models.LoggerContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.LoggerContract:
        """Creates or Updates a logger.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param logger_id: Logger identifier. Must be unique in the API Management service instance.
         Required.
        :type logger_id: str
        :param parameters: Create parameters. Is one of the following types: LoggerContract, JSON,
         IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.LoggerContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: LoggerContract. The LoggerContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.LoggerContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.LoggerContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_logger_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            logger_id=logger_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.LoggerContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        logger_id: str,
        parameters: _models.LoggerUpdateContract,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.LoggerContract:
        """Updates an existing logger.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param logger_id: Logger identifier. Must be unique in the API Management service instance.
         Required.
        :type logger_id: str
        :param parameters: Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.LoggerUpdateContract
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: LoggerContract. The LoggerContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.LoggerContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        logger_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.LoggerContract:
        """Updates an existing logger.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param logger_id: Logger identifier. Must be unique in the API Management service instance.
         Required.
        :type logger_id: str
        :param parameters: Update parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: LoggerContract. The LoggerContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.LoggerContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        logger_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.LoggerContract:
        """Updates an existing logger.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param logger_id: Logger identifier. Must be unique in the API Management service instance.
         Required.
        :type logger_id: str
        :param parameters: Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: LoggerContract. The LoggerContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.LoggerContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        logger_id: str,
        parameters: Union[_models.LoggerUpdateContract, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.LoggerContract:
        """Updates an existing logger.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param logger_id: Logger identifier. Must be unique in the API Management service instance.
         Required.
        :type logger_id: str
        :param parameters: Update parameters. Is one of the following types: LoggerUpdateContract,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.LoggerUpdateContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: LoggerContract. The LoggerContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.LoggerContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.LoggerContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_logger_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            logger_id=logger_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.LoggerContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        logger_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes the specified logger.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param logger_id: Logger identifier. Must be unique in the API Management service instance.
         Required.
        :type logger_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_logger_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            logger_id=logger_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_workspace(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.LoggerContract"]:
        """Lists a collection of loggers in the specified workspace.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         description | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>| loggerType | filter | eq |     |</br>| resourceId | filter | ge, le, eq, ne, gt, lt |
         substringof, contains, startswith, endswith |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of LoggerContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.LoggerContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.LoggerContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_workspace_logger_list_by_workspace_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    workspace_id=workspace_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.LoggerContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class WorkspaceNamedValueOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`workspace_named_value` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, workspace_id: str, named_value_id: str, **kwargs: Any
    ) -> _models.NamedValueContract:
        """Gets the details of the named value specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param named_value_id: Identifier of the NamedValue. Required.
        :type named_value_id: str
        :return: NamedValueContract. The NamedValueContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.NamedValueContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.NamedValueContract] = kwargs.pop("cls", None)

        _request = build_workspace_named_value_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            named_value_id=named_value_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.NamedValueContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, workspace_id: str, named_value_id: str, **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the named value specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param named_value_id: Identifier of the NamedValue. Required.
        :type named_value_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_named_value_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            named_value_id=named_value_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    async def _create_or_update_initial(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        named_value_id: str,
        parameters: Union[_models.NamedValueCreateContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_named_value_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            named_value_id=named_value_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 200:
            response_headers["Azure-AsyncOperation"] = self._deserialize(
                "str", response.headers.get("Azure-AsyncOperation")
            )
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if response.status_code == 201:
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))
            response_headers["Azure-AsyncOperation"] = self._deserialize(
                "str", response.headers.get("Azure-AsyncOperation")
            )
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        named_value_id: str,
        parameters: _models.NamedValueCreateContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.NamedValueContract]:
        """Creates or updates named value.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param named_value_id: Identifier of the NamedValue. Required.
        :type named_value_id: str
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.NamedValueCreateContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns NamedValueContract. The NamedValueContract
         is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.NamedValueContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        named_value_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.NamedValueContract]:
        """Creates or updates named value.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param named_value_id: Identifier of the NamedValue. Required.
        :type named_value_id: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns NamedValueContract. The NamedValueContract
         is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.NamedValueContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        named_value_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.NamedValueContract]:
        """Creates or updates named value.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param named_value_id: Identifier of the NamedValue. Required.
        :type named_value_id: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns NamedValueContract. The NamedValueContract
         is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.NamedValueContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        named_value_id: str,
        parameters: Union[_models.NamedValueCreateContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.NamedValueContract]:
        """Creates or updates named value.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param named_value_id: Identifier of the NamedValue. Required.
        :type named_value_id: str
        :param parameters: Create parameters. Is one of the following types: NamedValueCreateContract,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.NamedValueCreateContract or JSON or
         IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns NamedValueContract. The NamedValueContract
         is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.NamedValueContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.NamedValueContract] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._create_or_update_initial(
                resource_group_name=resource_group_name,
                service_name=service_name,
                workspace_id=workspace_id,
                named_value_id=named_value_id,
                parameters=parameters,
                etag=etag,
                match_condition=match_condition,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response_headers = {}
            response = pipeline_response.http_response
            response_headers["Azure-AsyncOperation"] = self._deserialize(
                "str", response.headers.get("Azure-AsyncOperation")
            )
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

            deserialized = _deserialize(_models.NamedValueContract, response.json())
            if cls:
                return cls(pipeline_response, deserialized, response_headers)  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.NamedValueContract].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.NamedValueContract](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _update_initial(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        named_value_id: str,
        parameters: Union[_models.NamedValueUpdateParameters, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_named_value_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            named_value_id=named_value_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 200:
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if response.status_code == 202:
            response_headers["Azure-AsyncOperation"] = self._deserialize(
                "str", response.headers.get("Azure-AsyncOperation")
            )
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        named_value_id: str,
        parameters: _models.NamedValueUpdateParameters,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.NamedValueContract]:
        """Updates the specific named value.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param named_value_id: Identifier of the NamedValue. Required.
        :type named_value_id: str
        :param parameters: Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.NamedValueUpdateParameters
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns NamedValueContract. The NamedValueContract
         is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.NamedValueContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        named_value_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.NamedValueContract]:
        """Updates the specific named value.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param named_value_id: Identifier of the NamedValue. Required.
        :type named_value_id: str
        :param parameters: Update parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns NamedValueContract. The NamedValueContract
         is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.NamedValueContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        named_value_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.NamedValueContract]:
        """Updates the specific named value.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param named_value_id: Identifier of the NamedValue. Required.
        :type named_value_id: str
        :param parameters: Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns NamedValueContract. The NamedValueContract
         is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.NamedValueContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        named_value_id: str,
        parameters: Union[_models.NamedValueUpdateParameters, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.NamedValueContract]:
        """Updates the specific named value.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param named_value_id: Identifier of the NamedValue. Required.
        :type named_value_id: str
        :param parameters: Update parameters. Is one of the following types:
         NamedValueUpdateParameters, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.NamedValueUpdateParameters or JSON or
         IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns NamedValueContract. The NamedValueContract
         is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.NamedValueContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.NamedValueContract] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._update_initial(
                resource_group_name=resource_group_name,
                service_name=service_name,
                workspace_id=workspace_id,
                named_value_id=named_value_id,
                parameters=parameters,
                etag=etag,
                match_condition=match_condition,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response_headers = {}
            response = pipeline_response.http_response
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

            deserialized = _deserialize(_models.NamedValueContract, response.json())
            if cls:
                return cls(pipeline_response, deserialized, response_headers)  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.NamedValueContract].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.NamedValueContract](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        named_value_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes specific named value from the workspace in an API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param named_value_id: Identifier of the NamedValue. Required.
        :type named_value_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_named_value_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            named_value_id=named_value_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        is_key_vault_refresh_failed: Optional[Union[str, _models.KeyVaultRefreshState]] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.NamedValueContract"]:
        """Lists a collection of named values defined within a workspace in a service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| tags |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith, any, all |</br>|
         displayName | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :keyword is_key_vault_refresh_failed: Query parameter to fetch named value entities based on
         refresh status. Known values are: "true" and "false". Default value is None.
        :paramtype is_key_vault_refresh_failed: str or
         ~azure.mgmt.apimanagement.models.KeyVaultRefreshState
        :return: An iterator like instance of NamedValueContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.NamedValueContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.NamedValueContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_workspace_named_value_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    workspace_id=workspace_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    is_key_vault_refresh_failed=is_key_vault_refresh_failed,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.NamedValueContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def list_value(
        self, resource_group_name: str, service_name: str, workspace_id: str, named_value_id: str, **kwargs: Any
    ) -> _models.NamedValueSecretContract:
        """Gets the secret of the named value specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param named_value_id: Identifier of the NamedValue. Required.
        :type named_value_id: str
        :return: NamedValueSecretContract. The NamedValueSecretContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.NamedValueSecretContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.NamedValueSecretContract] = kwargs.pop("cls", None)

        _request = build_workspace_named_value_list_value_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            named_value_id=named_value_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.NamedValueSecretContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    async def _refresh_secret_initial(
        self, resource_group_name: str, service_name: str, workspace_id: str, named_value_id: str, **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        _request = build_workspace_named_value_refresh_secret_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            named_value_id=named_value_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 200:
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if response.status_code == 202:
            response_headers["Azure-AsyncOperation"] = self._deserialize(
                "str", response.headers.get("Azure-AsyncOperation")
            )
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def begin_refresh_secret(
        self, resource_group_name: str, service_name: str, workspace_id: str, named_value_id: str, **kwargs: Any
    ) -> AsyncLROPoller[_models.NamedValueContract]:
        """Refresh the secret of the named value specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param named_value_id: Identifier of the NamedValue. Required.
        :type named_value_id: str
        :return: An instance of AsyncLROPoller that returns NamedValueContract. The NamedValueContract
         is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.NamedValueContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.NamedValueContract] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._refresh_secret_initial(
                resource_group_name=resource_group_name,
                service_name=service_name,
                workspace_id=workspace_id,
                named_value_id=named_value_id,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response_headers = {}
            response = pipeline_response.http_response
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

            deserialized = _deserialize(_models.NamedValueContract, response.json())
            if cls:
                return cls(pipeline_response, deserialized, response_headers)  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.NamedValueContract].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.NamedValueContract](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )


class WorkspaceNotificationOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`workspace_notification` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        notification_name: Union[str, _models.NotificationName],
        **kwargs: Any
    ) -> _models.NotificationContract:
        """Gets the details of the Notification specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param notification_name: Notification Name Identifier. Known values are:
         "RequestPublisherNotificationMessage", "PurchasePublisherNotificationMessage",
         "NewApplicationNotificationMessage", "BCC", "NewIssuePublisherNotificationMessage",
         "AccountClosedPublisher", and "QuotaLimitApproachingPublisherNotificationMessage". Required.
        :type notification_name: str or ~azure.mgmt.apimanagement.models.NotificationName
        :return: NotificationContract. The NotificationContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.NotificationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.NotificationContract] = kwargs.pop("cls", None)

        _request = build_workspace_notification_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            notification_name=notification_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.NotificationContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        notification_name: Union[str, _models.NotificationName],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.NotificationContract:
        """Create or Update API Management publisher notification for the workspace.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param notification_name: Notification Name Identifier. Known values are:
         "RequestPublisherNotificationMessage", "PurchasePublisherNotificationMessage",
         "NewApplicationNotificationMessage", "BCC", "NewIssuePublisherNotificationMessage",
         "AccountClosedPublisher", and "QuotaLimitApproachingPublisherNotificationMessage". Required.
        :type notification_name: str or ~azure.mgmt.apimanagement.models.NotificationName
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: NotificationContract. The NotificationContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.NotificationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.NotificationContract] = kwargs.pop("cls", None)

        _request = build_workspace_notification_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            notification_name=notification_name,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.NotificationContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        *,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.NotificationContract"]:
        """Lists a collection of properties defined within a service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of NotificationContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.NotificationContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.NotificationContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_workspace_notification_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    workspace_id=workspace_id,
                    subscription_id=self._config.subscription_id,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.NotificationContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class WorkspacePolicyFragmentOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`workspace_policy_fragment` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        id: str,
        *,
        format: Optional[Union[str, _models.PolicyFragmentContentFormat]] = None,
        **kwargs: Any
    ) -> _models.PolicyFragmentContract:
        """Gets a policy fragment.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param id: A resource identifier. Required.
        :type id: str
        :keyword format: Policy fragment content format. Known values are: "xml" and "rawxml". Default
         value is None.
        :paramtype format: str or ~azure.mgmt.apimanagement.models.PolicyFragmentContentFormat
        :return: PolicyFragmentContract. The PolicyFragmentContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyFragmentContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.PolicyFragmentContract] = kwargs.pop("cls", None)

        _request = build_workspace_policy_fragment_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            id=id,
            subscription_id=self._config.subscription_id,
            format=format,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PolicyFragmentContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, workspace_id: str, id: str, **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of a policy fragment.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param id: A resource identifier. Required.
        :type id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_policy_fragment_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            id=id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    async def _create_or_update_initial(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        id: str,
        parameters: Union[_models.PolicyFragmentContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_policy_fragment_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            id=id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["Azure-AsyncOperation"] = self._deserialize(
            "str", response.headers.get("Azure-AsyncOperation")
        )
        response_headers["location"] = self._deserialize("str", response.headers.get("location"))
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        id: str,
        parameters: _models.PolicyFragmentContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.PolicyFragmentContract]:
        """Creates or updates a policy fragment.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param id: A resource identifier. Required.
        :type id: str
        :param parameters: The policy fragment contents to apply. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PolicyFragmentContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns PolicyFragmentContract. The
         PolicyFragmentContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.PolicyFragmentContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.PolicyFragmentContract]:
        """Creates or updates a policy fragment.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param id: A resource identifier. Required.
        :type id: str
        :param parameters: The policy fragment contents to apply. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns PolicyFragmentContract. The
         PolicyFragmentContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.PolicyFragmentContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.PolicyFragmentContract]:
        """Creates or updates a policy fragment.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param id: A resource identifier. Required.
        :type id: str
        :param parameters: The policy fragment contents to apply. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns PolicyFragmentContract. The
         PolicyFragmentContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.PolicyFragmentContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        id: str,
        parameters: Union[_models.PolicyFragmentContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.PolicyFragmentContract]:
        """Creates or updates a policy fragment.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param id: A resource identifier. Required.
        :type id: str
        :param parameters: The policy fragment contents to apply. Is one of the following types:
         PolicyFragmentContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PolicyFragmentContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns PolicyFragmentContract. The
         PolicyFragmentContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.PolicyFragmentContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.PolicyFragmentContract] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._create_or_update_initial(
                resource_group_name=resource_group_name,
                service_name=service_name,
                workspace_id=workspace_id,
                id=id,
                parameters=parameters,
                etag=etag,
                match_condition=match_condition,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response_headers = {}
            response = pipeline_response.http_response
            response_headers["Azure-AsyncOperation"] = self._deserialize(
                "str", response.headers.get("Azure-AsyncOperation")
            )
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

            deserialized = _deserialize(_models.PolicyFragmentContract, response.json())
            if cls:
                return cls(pipeline_response, deserialized, response_headers)  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.PolicyFragmentContract].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.PolicyFragmentContract](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes a policy fragment.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param id: A resource identifier. Required.
        :type id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_policy_fragment_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            id=id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        *,
        filter: Optional[str] = None,
        orderby: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.PolicyFragmentContract"]:
        """Gets all policy fragments defined within a workspace.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter, orderBy | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         description | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>| value | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>. Default value is None.
        :paramtype filter: str
        :keyword orderby: OData order by query option. Default value is None.
        :paramtype orderby: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of PolicyFragmentContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.PolicyFragmentContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.PolicyFragmentContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_workspace_policy_fragment_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    workspace_id=workspace_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    orderby=orderby,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.PolicyFragmentContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def list_references(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        id: str,
        *,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> _models.ResourceCollection:
        """Lists policy resources that reference the policy fragment.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param id: A resource identifier. Required.
        :type id: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: ResourceCollection. The ResourceCollection is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ResourceCollection
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ResourceCollection] = kwargs.pop("cls", None)

        _request = build_workspace_policy_fragment_list_references_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            id=id,
            subscription_id=self._config.subscription_id,
            top=top,
            skip=skip,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ResourceCollection, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class SignInSettingsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`sign_in_settings` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(self, resource_group_name: str, service_name: str, **kwargs: Any) -> _models.PortalSigninSettings:
        """Get Sign In Settings for the Portal.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :return: PortalSigninSettings. The PortalSigninSettings is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PortalSigninSettings
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.PortalSigninSettings] = kwargs.pop("cls", None)

        _request = build_sign_in_settings_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PortalSigninSettings, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(self, resource_group_name: str, service_name: str, **kwargs: Any) -> bool:
        """Gets the entity state (Etag) version of the SignInSettings.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_sign_in_settings_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: _models.PortalSigninSettings,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PortalSigninSettings:
        """Create or Update Sign-In settings.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Create or update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PortalSigninSettings
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PortalSigninSettings. The PortalSigninSettings is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PortalSigninSettings
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PortalSigninSettings:
        """Create or Update Sign-In settings.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Create or update parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PortalSigninSettings. The PortalSigninSettings is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PortalSigninSettings
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PortalSigninSettings:
        """Create or Update Sign-In settings.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Create or update parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PortalSigninSettings. The PortalSigninSettings is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PortalSigninSettings
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: Union[_models.PortalSigninSettings, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PortalSigninSettings:
        """Create or Update Sign-In settings.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Create or update parameters. Is one of the following types:
         PortalSigninSettings, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PortalSigninSettings or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PortalSigninSettings. The PortalSigninSettings is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PortalSigninSettings
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.PortalSigninSettings] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_sign_in_settings_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PortalSigninSettings, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: _models.PortalSigninSettings,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> None:
        """Update Sign-In settings.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Update Sign-In settings. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PortalSigninSettings
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> None:
        """Update Sign-In settings.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Update Sign-In settings. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> None:
        """Update Sign-In settings.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Update Sign-In settings. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: Union[_models.PortalSigninSettings, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Update Sign-In settings.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Update Sign-In settings. Is one of the following types:
         PortalSigninSettings, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PortalSigninSettings or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[None] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_sign_in_settings_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore


class SignUpSettingsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`sign_up_settings` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(self, resource_group_name: str, service_name: str, **kwargs: Any) -> _models.PortalSignupSettings:
        """Get Sign Up Settings for the Portal.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :return: PortalSignupSettings. The PortalSignupSettings is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PortalSignupSettings
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.PortalSignupSettings] = kwargs.pop("cls", None)

        _request = build_sign_up_settings_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PortalSignupSettings, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(self, resource_group_name: str, service_name: str, **kwargs: Any) -> bool:
        """Gets the entity state (Etag) version of the SignUpSettings.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_sign_up_settings_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: _models.PortalSignupSettings,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PortalSignupSettings:
        """Create or Update Sign-Up settings.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Create or update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PortalSignupSettings
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PortalSignupSettings. The PortalSignupSettings is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PortalSignupSettings
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PortalSignupSettings:
        """Create or Update Sign-Up settings.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Create or update parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PortalSignupSettings. The PortalSignupSettings is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PortalSignupSettings
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PortalSignupSettings:
        """Create or Update Sign-Up settings.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Create or update parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PortalSignupSettings. The PortalSignupSettings is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PortalSignupSettings
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: Union[_models.PortalSignupSettings, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PortalSignupSettings:
        """Create or Update Sign-Up settings.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Create or update parameters. Is one of the following types:
         PortalSignupSettings, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PortalSignupSettings or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PortalSignupSettings. The PortalSignupSettings is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PortalSignupSettings
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.PortalSignupSettings] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_sign_up_settings_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PortalSignupSettings, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: _models.PortalSignupSettings,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> None:
        """Update Sign-Up settings.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Update Sign-Up settings. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PortalSignupSettings
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> None:
        """Update Sign-Up settings.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Update Sign-Up settings. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> None:
        """Update Sign-Up settings.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Update Sign-Up settings. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: Union[_models.PortalSignupSettings, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Update Sign-Up settings.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Update Sign-Up settings. Is one of the following types:
         PortalSignupSettings, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PortalSignupSettings or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[None] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_sign_up_settings_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore


class DelegationSettingsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`delegation_settings` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(self, resource_group_name: str, service_name: str, **kwargs: Any) -> _models.PortalDelegationSettings:
        """Get Delegation Settings for the Portal.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :return: PortalDelegationSettings. The PortalDelegationSettings is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PortalDelegationSettings
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.PortalDelegationSettings] = kwargs.pop("cls", None)

        _request = build_delegation_settings_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PortalDelegationSettings, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(self, resource_group_name: str, service_name: str, **kwargs: Any) -> bool:
        """Gets the entity state (Etag) version of the DelegationSettings.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_delegation_settings_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: _models.PortalDelegationSettings,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PortalDelegationSettings:
        """Create or Update Delegation settings.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Create or update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PortalDelegationSettings
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PortalDelegationSettings. The PortalDelegationSettings is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PortalDelegationSettings
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PortalDelegationSettings:
        """Create or Update Delegation settings.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Create or update parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PortalDelegationSettings. The PortalDelegationSettings is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PortalDelegationSettings
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PortalDelegationSettings:
        """Create or Update Delegation settings.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Create or update parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PortalDelegationSettings. The PortalDelegationSettings is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PortalDelegationSettings
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: Union[_models.PortalDelegationSettings, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PortalDelegationSettings:
        """Create or Update Delegation settings.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Create or update parameters. Is one of the following types:
         PortalDelegationSettings, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PortalDelegationSettings or JSON or
         IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PortalDelegationSettings. The PortalDelegationSettings is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PortalDelegationSettings
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.PortalDelegationSettings] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_delegation_settings_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PortalDelegationSettings, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: _models.PortalDelegationSettings,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> None:
        """Update Delegation settings.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Update Delegation settings. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PortalDelegationSettings
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> None:
        """Update Delegation settings.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Update Delegation settings. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> None:
        """Update Delegation settings.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Update Delegation settings. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: Union[_models.PortalDelegationSettings, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Update Delegation settings.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Update Delegation settings. Is one of the following types:
         PortalDelegationSettings, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PortalDelegationSettings or JSON or
         IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[None] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_delegation_settings_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace_async
    async def list_secrets(
        self, resource_group_name: str, service_name: str, **kwargs: Any
    ) -> _models.PortalSettingValidationKeyContract:
        """Gets the secret validation key of the DelegationSettings.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :return: PortalSettingValidationKeyContract. The PortalSettingValidationKeyContract is
         compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PortalSettingValidationKeyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.PortalSettingValidationKeyContract] = kwargs.pop("cls", None)

        _request = build_delegation_settings_list_secrets_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PortalSettingValidationKeyContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class WorkspaceProductOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`workspace_product` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, workspace_id: str, product_id: str, **kwargs: Any
    ) -> _models.ProductContract:
        """Gets the details of the product specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :return: ProductContract. The ProductContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ProductContract] = kwargs.pop("cls", None)

        _request = build_workspace_product_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            product_id=product_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ProductContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, workspace_id: str, product_id: str, **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the product specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_product_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            product_id=product_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        product_id: str,
        parameters: _models.ProductContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ProductContract:
        """Creates or Updates a product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ProductContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ProductContract. The ProductContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        product_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ProductContract:
        """Creates or Updates a product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ProductContract. The ProductContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        product_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ProductContract:
        """Creates or Updates a product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ProductContract. The ProductContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        product_id: str,
        parameters: Union[_models.ProductContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ProductContract:
        """Creates or Updates a product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param parameters: Create or update parameters. Is one of the following types: ProductContract,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ProductContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ProductContract. The ProductContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ProductContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_product_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            product_id=product_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ProductContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        product_id: str,
        parameters: _models.ProductUpdateParameters,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ProductContract:
        """Update existing product details.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param parameters: Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ProductUpdateParameters
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ProductContract. The ProductContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        product_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ProductContract:
        """Update existing product details.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param parameters: Update parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ProductContract. The ProductContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        product_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ProductContract:
        """Update existing product details.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param parameters: Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ProductContract. The ProductContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        product_id: str,
        parameters: Union[_models.ProductUpdateParameters, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.ProductContract:
        """Update existing product details.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param parameters: Update parameters. Is one of the following types: ProductUpdateParameters,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ProductUpdateParameters or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ProductContract. The ProductContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ProductContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_product_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            product_id=product_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ProductContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        product_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        delete_subscriptions: Optional[bool] = None,
        **kwargs: Any
    ) -> None:
        """Delete product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword delete_subscriptions: Delete existing subscriptions associated with the product or
         not. Default value is None.
        :paramtype delete_subscriptions: bool
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_product_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            product_id=product_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            delete_subscriptions=delete_subscriptions,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        expand_groups: Optional[bool] = None,
        tags: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.ProductContract"]:
        """Lists a collection of products in the specified workspace in a service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         displayName | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>| description | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
         endswith |</br>| terms | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
         endswith |</br>| state | filter | eq |     |</br>| groups | expand |     |     |</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :keyword expand_groups: When set to true, the response contains an array of groups that have
         visibility to the product. The default is false. Default value is None.
        :paramtype expand_groups: bool
        :keyword tags: Products which are part of a specific tag. Default value is None.
        :paramtype tags: str
        :return: An iterator like instance of ProductContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ProductContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ProductContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_workspace_product_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    workspace_id=workspace_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    expand_groups=expand_groups,
                    tags=tags,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ProductContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class WorkspaceProductApiLinkOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`workspace_product_api_link` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        product_id: str,
        api_link_id: str,
        **kwargs: Any
    ) -> _models.ProductApiLinkContract:
        """Gets the API link for the product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param api_link_id: Product-API link identifier. Must be unique in the current API Management
         service instance. Required.
        :type api_link_id: str
        :return: ProductApiLinkContract. The ProductApiLinkContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductApiLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ProductApiLinkContract] = kwargs.pop("cls", None)

        _request = build_workspace_product_api_link_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            product_id=product_id,
            api_link_id=api_link_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ProductApiLinkContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        product_id: str,
        api_link_id: str,
        parameters: _models.ProductApiLinkContract,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ProductApiLinkContract:
        """Adds an API to the specified product via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param api_link_id: Product-API link identifier. Must be unique in the current API Management
         service instance. Required.
        :type api_link_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ProductApiLinkContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ProductApiLinkContract. The ProductApiLinkContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductApiLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        product_id: str,
        api_link_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ProductApiLinkContract:
        """Adds an API to the specified product via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param api_link_id: Product-API link identifier. Must be unique in the current API Management
         service instance. Required.
        :type api_link_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ProductApiLinkContract. The ProductApiLinkContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductApiLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        product_id: str,
        api_link_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ProductApiLinkContract:
        """Adds an API to the specified product via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param api_link_id: Product-API link identifier. Must be unique in the current API Management
         service instance. Required.
        :type api_link_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ProductApiLinkContract. The ProductApiLinkContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductApiLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        product_id: str,
        api_link_id: str,
        parameters: Union[_models.ProductApiLinkContract, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.ProductApiLinkContract:
        """Adds an API to the specified product via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param api_link_id: Product-API link identifier. Must be unique in the current API Management
         service instance. Required.
        :type api_link_id: str
        :param parameters: Create or update parameters. Is one of the following types:
         ProductApiLinkContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ProductApiLinkContract or JSON or IO[bytes]
        :return: ProductApiLinkContract. The ProductApiLinkContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductApiLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ProductApiLinkContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_product_api_link_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            product_id=product_id,
            api_link_id=api_link_id,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ProductApiLinkContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        product_id: str,
        api_link_id: str,
        **kwargs: Any
    ) -> None:
        """Deletes the specified API from the specified product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param api_link_id: Product-API link identifier. Must be unique in the current API Management
         service instance. Required.
        :type api_link_id: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_product_api_link_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            product_id=product_id,
            api_link_id=api_link_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_product(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        product_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.ProductApiLinkContract"]:
        """Lists a collection of the API links associated with a product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| apiId |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of ProductApiLinkContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ProductApiLinkContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ProductApiLinkContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_workspace_product_api_link_list_by_product_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    workspace_id=workspace_id,
                    product_id=product_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ProductApiLinkContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class WorkspaceProductGroupLinkOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`workspace_product_group_link` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        product_id: str,
        group_link_id: str,
        **kwargs: Any
    ) -> _models.ProductGroupLinkContract:
        """Gets the group link for the product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param group_link_id: Product-Group link identifier. Must be unique in the current API
         Management service instance. Required.
        :type group_link_id: str
        :return: ProductGroupLinkContract. The ProductGroupLinkContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductGroupLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ProductGroupLinkContract] = kwargs.pop("cls", None)

        _request = build_workspace_product_group_link_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            product_id=product_id,
            group_link_id=group_link_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ProductGroupLinkContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        product_id: str,
        group_link_id: str,
        parameters: _models.ProductGroupLinkContract,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ProductGroupLinkContract:
        """Adds a group to the specified product via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param group_link_id: Product-Group link identifier. Must be unique in the current API
         Management service instance. Required.
        :type group_link_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ProductGroupLinkContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ProductGroupLinkContract. The ProductGroupLinkContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductGroupLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        product_id: str,
        group_link_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ProductGroupLinkContract:
        """Adds a group to the specified product via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param group_link_id: Product-Group link identifier. Must be unique in the current API
         Management service instance. Required.
        :type group_link_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ProductGroupLinkContract. The ProductGroupLinkContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductGroupLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        product_id: str,
        group_link_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ProductGroupLinkContract:
        """Adds a group to the specified product via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param group_link_id: Product-Group link identifier. Must be unique in the current API
         Management service instance. Required.
        :type group_link_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ProductGroupLinkContract. The ProductGroupLinkContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductGroupLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        product_id: str,
        group_link_id: str,
        parameters: Union[_models.ProductGroupLinkContract, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.ProductGroupLinkContract:
        """Adds a group to the specified product via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param group_link_id: Product-Group link identifier. Must be unique in the current API
         Management service instance. Required.
        :type group_link_id: str
        :param parameters: Create or update parameters. Is one of the following types:
         ProductGroupLinkContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ProductGroupLinkContract or JSON or
         IO[bytes]
        :return: ProductGroupLinkContract. The ProductGroupLinkContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductGroupLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ProductGroupLinkContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_product_group_link_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            product_id=product_id,
            group_link_id=group_link_id,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ProductGroupLinkContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        product_id: str,
        group_link_id: str,
        **kwargs: Any
    ) -> None:
        """Deletes the specified group from the specified product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param group_link_id: Product-Group link identifier. Must be unique in the current API
         Management service instance. Required.
        :type group_link_id: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_product_group_link_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            product_id=product_id,
            group_link_id=group_link_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_product(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        product_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.ProductGroupLinkContract"]:
        """Lists a collection of the group links associated with a product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| groupId |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of ProductGroupLinkContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ProductGroupLinkContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ProductGroupLinkContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_workspace_product_group_link_list_by_product_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    workspace_id=workspace_id,
                    product_id=product_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ProductGroupLinkContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class WorkspaceGlobalSchemaOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`workspace_global_schema` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, workspace_id: str, schema_id: str, **kwargs: Any
    ) -> _models.GlobalSchemaContract:
        """Gets the details of the Schema specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param schema_id: Schema id identifier. Must be unique in the current API Management service
         instance. Required.
        :type schema_id: str
        :return: GlobalSchemaContract. The GlobalSchemaContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GlobalSchemaContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.GlobalSchemaContract] = kwargs.pop("cls", None)

        _request = build_workspace_global_schema_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            schema_id=schema_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.GlobalSchemaContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, workspace_id: str, schema_id: str, **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the Schema specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param schema_id: Schema id identifier. Must be unique in the current API Management service
         instance. Required.
        :type schema_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_global_schema_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            schema_id=schema_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    async def _create_or_update_initial(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        schema_id: str,
        parameters: Union[_models.GlobalSchemaContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_global_schema_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            schema_id=schema_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["Azure-AsyncOperation"] = self._deserialize(
            "str", response.headers.get("Azure-AsyncOperation")
        )
        response_headers["location"] = self._deserialize("str", response.headers.get("location"))
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        schema_id: str,
        parameters: _models.GlobalSchemaContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.GlobalSchemaContract]:
        """Creates new or updates existing specified Schema of the workspace in an API Management service
        instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param schema_id: Schema id identifier. Must be unique in the current API Management service
         instance. Required.
        :type schema_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.GlobalSchemaContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns GlobalSchemaContract. The
         GlobalSchemaContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.GlobalSchemaContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        schema_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.GlobalSchemaContract]:
        """Creates new or updates existing specified Schema of the workspace in an API Management service
        instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param schema_id: Schema id identifier. Must be unique in the current API Management service
         instance. Required.
        :type schema_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns GlobalSchemaContract. The
         GlobalSchemaContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.GlobalSchemaContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        schema_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.GlobalSchemaContract]:
        """Creates new or updates existing specified Schema of the workspace in an API Management service
        instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param schema_id: Schema id identifier. Must be unique in the current API Management service
         instance. Required.
        :type schema_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns GlobalSchemaContract. The
         GlobalSchemaContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.GlobalSchemaContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        schema_id: str,
        parameters: Union[_models.GlobalSchemaContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.GlobalSchemaContract]:
        """Creates new or updates existing specified Schema of the workspace in an API Management service
        instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param schema_id: Schema id identifier. Must be unique in the current API Management service
         instance. Required.
        :type schema_id: str
        :param parameters: Create or update parameters. Is one of the following types:
         GlobalSchemaContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.GlobalSchemaContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns GlobalSchemaContract. The
         GlobalSchemaContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.GlobalSchemaContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.GlobalSchemaContract] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._create_or_update_initial(
                resource_group_name=resource_group_name,
                service_name=service_name,
                workspace_id=workspace_id,
                schema_id=schema_id,
                parameters=parameters,
                etag=etag,
                match_condition=match_condition,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response_headers = {}
            response = pipeline_response.http_response
            response_headers["Azure-AsyncOperation"] = self._deserialize(
                "str", response.headers.get("Azure-AsyncOperation")
            )
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

            deserialized = _deserialize(_models.GlobalSchemaContract, response.json())
            if cls:
                return cls(pipeline_response, deserialized, response_headers)  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.GlobalSchemaContract].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.GlobalSchemaContract](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        schema_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes specific Schema.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param schema_id: Schema id identifier. Must be unique in the current API Management service
         instance. Required.
        :type schema_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_global_schema_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            schema_id=schema_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.GlobalSchemaContract"]:
        """Lists a collection of schemas registered with workspace in a service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of GlobalSchemaContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.GlobalSchemaContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.GlobalSchemaContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_workspace_global_schema_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    workspace_id=workspace_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.GlobalSchemaContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class UserSubscriptionOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`user_subscription` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, user_id: str, sid: str, **kwargs: Any
    ) -> _models.SubscriptionContract:
        """Gets the specified Subscription entity associated with a particular user.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param user_id: User identifier. Must be unique in the current API Management service instance.
         Required.
        :type user_id: str
        :param sid: Subscription entity Identifier. The entity represents the association between a
         user and a product in API Management. Required.
        :type sid: str
        :return: SubscriptionContract. The SubscriptionContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.SubscriptionContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.SubscriptionContract] = kwargs.pop("cls", None)

        _request = build_user_subscription_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            user_id=user_id,
            sid=sid,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.SubscriptionContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list(
        self,
        resource_group_name: str,
        service_name: str,
        user_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.SubscriptionContract"]:
        """Lists the collection of subscriptions of the specified user.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param user_id: User identifier. Must be unique in the current API Management service instance.
         Required.
        :type user_id: str
        :keyword filter: | Field     |     Usage     |     Supported operators    | Supported functions
         |</br>|-------------|------------------------|-----------------------------------|</br>|name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>|displayName | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
         endswith |</br>|stateComment | filter | ge, le, eq, ne, gt, lt | substringof, contains,
         startswith, endswith |</br>|ownerId | filter | ge, le, eq, ne, gt, lt | substringof, contains,
         startswith, endswith |</br>|scope | filter | ge, le, eq, ne, gt, lt | substringof, contains,
         startswith, endswith |</br>|userId | filter | ge, le, eq, ne, gt, lt | substringof, contains,
         startswith, endswith |</br>|productId | filter | ge, le, eq, ne, gt, lt | substringof,
         contains, startswith, endswith |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of SubscriptionContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.SubscriptionContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.SubscriptionContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_user_subscription_list_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    user_id=user_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.SubscriptionContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class WorkspaceSubscriptionOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`workspace_subscription` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, workspace_id: str, sid: str, **kwargs: Any
    ) -> _models.SubscriptionContract:
        """Gets the specified Subscription entity.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param sid: Subscription entity Identifier. The entity represents the association between a
         user and a product in API Management. Required.
        :type sid: str
        :return: SubscriptionContract. The SubscriptionContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.SubscriptionContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.SubscriptionContract] = kwargs.pop("cls", None)

        _request = build_workspace_subscription_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            sid=sid,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.SubscriptionContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, workspace_id: str, sid: str, **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the apimanagement subscription specified by its
        identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param sid: Subscription entity Identifier. The entity represents the association between a
         user and a product in API Management. Required.
        :type sid: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_subscription_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            sid=sid,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        sid: str,
        parameters: _models.SubscriptionCreateParameters,
        *,
        notify: Optional[bool] = None,
        app_type: Optional[Union[str, _models.AppType]] = None,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.SubscriptionContract:
        """Creates or updates the subscription of specified user to the specified product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param sid: Subscription entity Identifier. The entity represents the association between a
         user and a product in API Management. Required.
        :type sid: str
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.SubscriptionCreateParameters
        :keyword notify: Notify change in Subscription State.

         * If false, do not send any email notification for change of state of subscription
         * If true, send email notification of change of state of subscription. Default value is None.
        :paramtype notify: bool
        :keyword app_type: Determines the type of application which send the create user request.
         Default is legacy publisher portal. Known values are: "portal" and "developerPortal". Default
         value is None.
        :paramtype app_type: str or ~azure.mgmt.apimanagement.models.AppType
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: SubscriptionContract. The SubscriptionContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.SubscriptionContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        sid: str,
        parameters: JSON,
        *,
        notify: Optional[bool] = None,
        app_type: Optional[Union[str, _models.AppType]] = None,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.SubscriptionContract:
        """Creates or updates the subscription of specified user to the specified product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param sid: Subscription entity Identifier. The entity represents the association between a
         user and a product in API Management. Required.
        :type sid: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword notify: Notify change in Subscription State.

         * If false, do not send any email notification for change of state of subscription
         * If true, send email notification of change of state of subscription. Default value is None.
        :paramtype notify: bool
        :keyword app_type: Determines the type of application which send the create user request.
         Default is legacy publisher portal. Known values are: "portal" and "developerPortal". Default
         value is None.
        :paramtype app_type: str or ~azure.mgmt.apimanagement.models.AppType
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: SubscriptionContract. The SubscriptionContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.SubscriptionContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        sid: str,
        parameters: IO[bytes],
        *,
        notify: Optional[bool] = None,
        app_type: Optional[Union[str, _models.AppType]] = None,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.SubscriptionContract:
        """Creates or updates the subscription of specified user to the specified product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param sid: Subscription entity Identifier. The entity represents the association between a
         user and a product in API Management. Required.
        :type sid: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword notify: Notify change in Subscription State.

         * If false, do not send any email notification for change of state of subscription
         * If true, send email notification of change of state of subscription. Default value is None.
        :paramtype notify: bool
        :keyword app_type: Determines the type of application which send the create user request.
         Default is legacy publisher portal. Known values are: "portal" and "developerPortal". Default
         value is None.
        :paramtype app_type: str or ~azure.mgmt.apimanagement.models.AppType
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: SubscriptionContract. The SubscriptionContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.SubscriptionContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        sid: str,
        parameters: Union[_models.SubscriptionCreateParameters, JSON, IO[bytes]],
        *,
        notify: Optional[bool] = None,
        app_type: Optional[Union[str, _models.AppType]] = None,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.SubscriptionContract:
        """Creates or updates the subscription of specified user to the specified product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param sid: Subscription entity Identifier. The entity represents the association between a
         user and a product in API Management. Required.
        :type sid: str
        :param parameters: Create parameters. Is one of the following types:
         SubscriptionCreateParameters, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.SubscriptionCreateParameters or JSON or
         IO[bytes]
        :keyword notify: Notify change in Subscription State.

         * If false, do not send any email notification for change of state of subscription
         * If true, send email notification of change of state of subscription. Default value is None.
        :paramtype notify: bool
        :keyword app_type: Determines the type of application which send the create user request.
         Default is legacy publisher portal. Known values are: "portal" and "developerPortal". Default
         value is None.
        :paramtype app_type: str or ~azure.mgmt.apimanagement.models.AppType
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: SubscriptionContract. The SubscriptionContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.SubscriptionContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.SubscriptionContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_subscription_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            sid=sid,
            subscription_id=self._config.subscription_id,
            notify=notify,
            app_type=app_type,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.SubscriptionContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        sid: str,
        parameters: _models.SubscriptionUpdateParameters,
        *,
        etag: str,
        match_condition: MatchConditions,
        notify: Optional[bool] = None,
        app_type: Optional[Union[str, _models.AppType]] = None,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.SubscriptionContract:
        """Updates the details of a subscription specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param sid: Subscription entity Identifier. The entity represents the association between a
         user and a product in API Management. Required.
        :type sid: str
        :param parameters: Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.SubscriptionUpdateParameters
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword notify: Notify change in Subscription State.

         * If false, do not send any email notification for change of state of subscription
         * If true, send email notification of change of state of subscription. Default value is None.
        :paramtype notify: bool
        :keyword app_type: Determines the type of application which send the create user request.
         Default is legacy publisher portal. Known values are: "portal" and "developerPortal". Default
         value is None.
        :paramtype app_type: str or ~azure.mgmt.apimanagement.models.AppType
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: SubscriptionContract. The SubscriptionContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.SubscriptionContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        sid: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        notify: Optional[bool] = None,
        app_type: Optional[Union[str, _models.AppType]] = None,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.SubscriptionContract:
        """Updates the details of a subscription specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param sid: Subscription entity Identifier. The entity represents the association between a
         user and a product in API Management. Required.
        :type sid: str
        :param parameters: Update parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword notify: Notify change in Subscription State.

         * If false, do not send any email notification for change of state of subscription
         * If true, send email notification of change of state of subscription. Default value is None.
        :paramtype notify: bool
        :keyword app_type: Determines the type of application which send the create user request.
         Default is legacy publisher portal. Known values are: "portal" and "developerPortal". Default
         value is None.
        :paramtype app_type: str or ~azure.mgmt.apimanagement.models.AppType
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: SubscriptionContract. The SubscriptionContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.SubscriptionContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        sid: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        notify: Optional[bool] = None,
        app_type: Optional[Union[str, _models.AppType]] = None,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.SubscriptionContract:
        """Updates the details of a subscription specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param sid: Subscription entity Identifier. The entity represents the association between a
         user and a product in API Management. Required.
        :type sid: str
        :param parameters: Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword notify: Notify change in Subscription State.

         * If false, do not send any email notification for change of state of subscription
         * If true, send email notification of change of state of subscription. Default value is None.
        :paramtype notify: bool
        :keyword app_type: Determines the type of application which send the create user request.
         Default is legacy publisher portal. Known values are: "portal" and "developerPortal". Default
         value is None.
        :paramtype app_type: str or ~azure.mgmt.apimanagement.models.AppType
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: SubscriptionContract. The SubscriptionContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.SubscriptionContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        sid: str,
        parameters: Union[_models.SubscriptionUpdateParameters, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        notify: Optional[bool] = None,
        app_type: Optional[Union[str, _models.AppType]] = None,
        **kwargs: Any
    ) -> _models.SubscriptionContract:
        """Updates the details of a subscription specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param sid: Subscription entity Identifier. The entity represents the association between a
         user and a product in API Management. Required.
        :type sid: str
        :param parameters: Update parameters. Is one of the following types:
         SubscriptionUpdateParameters, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.SubscriptionUpdateParameters or JSON or
         IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword notify: Notify change in Subscription State.

         * If false, do not send any email notification for change of state of subscription
         * If true, send email notification of change of state of subscription. Default value is None.
        :paramtype notify: bool
        :keyword app_type: Determines the type of application which send the create user request.
         Default is legacy publisher portal. Known values are: "portal" and "developerPortal". Default
         value is None.
        :paramtype app_type: str or ~azure.mgmt.apimanagement.models.AppType
        :return: SubscriptionContract. The SubscriptionContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.SubscriptionContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.SubscriptionContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_subscription_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            sid=sid,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            notify=notify,
            app_type=app_type,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.SubscriptionContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        sid: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes the specified subscription.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param sid: Subscription entity Identifier. The entity represents the association between a
         user and a product in API Management. Required.
        :type sid: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_subscription_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            sid=sid,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.SubscriptionContract"]:
        """Lists all subscriptions of the workspace in an API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         displayName | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>| stateComment | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
         endswith |</br>| ownerId | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
         endswith |</br>| scope | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
         endswith |</br>| userId | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
         endswith |</br>| productId | filter | ge, le, eq, ne, gt, lt | substringof, contains,
         startswith, endswith |</br>| state | filter | eq |     |</br>| user | expand |     |
         |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of SubscriptionContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.SubscriptionContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.SubscriptionContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_workspace_subscription_list_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    workspace_id=workspace_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.SubscriptionContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def regenerate_primary_key(
        self, resource_group_name: str, service_name: str, workspace_id: str, sid: str, **kwargs: Any
    ) -> None:
        """Regenerates primary key of existing subscription of the workspace in an API Management service
        instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param sid: Subscription entity Identifier. The entity represents the association between a
         user and a product in API Management. Required.
        :type sid: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_subscription_regenerate_primary_key_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            sid=sid,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace_async
    async def regenerate_secondary_key(
        self, resource_group_name: str, service_name: str, workspace_id: str, sid: str, **kwargs: Any
    ) -> None:
        """Regenerates secondary key of existing subscription of the workspace in an API Management
        service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param sid: Subscription entity Identifier. The entity represents the association between a
         user and a product in API Management. Required.
        :type sid: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_subscription_regenerate_secondary_key_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            sid=sid,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace_async
    async def list_secrets(
        self, resource_group_name: str, service_name: str, workspace_id: str, sid: str, **kwargs: Any
    ) -> _models.SubscriptionKeysContract:
        """Gets the specified Subscription keys.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param sid: Subscription entity Identifier. The entity represents the association between a
         user and a product in API Management. Required.
        :type sid: str
        :return: SubscriptionKeysContract. The SubscriptionKeysContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.SubscriptionKeysContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.SubscriptionKeysContract] = kwargs.pop("cls", None)

        _request = build_workspace_subscription_list_secrets_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            sid=sid,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.SubscriptionKeysContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore


class WorkspaceTagApiLinkOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`workspace_tag_api_link` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        tag_id: str,
        api_link_id: str,
        **kwargs: Any
    ) -> _models.TagApiLinkContract:
        """Gets the API link for the tag.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param api_link_id: Tag-API link identifier. Must be unique in the current API Management
         service instance. Required.
        :type api_link_id: str
        :return: TagApiLinkContract. The TagApiLinkContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagApiLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.TagApiLinkContract] = kwargs.pop("cls", None)

        _request = build_workspace_tag_api_link_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            tag_id=tag_id,
            api_link_id=api_link_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.TagApiLinkContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        tag_id: str,
        api_link_id: str,
        parameters: _models.TagApiLinkContract,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.TagApiLinkContract:
        """Adds an API to the specified tag via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param api_link_id: Tag-API link identifier. Must be unique in the current API Management
         service instance. Required.
        :type api_link_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.TagApiLinkContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: TagApiLinkContract. The TagApiLinkContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagApiLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        tag_id: str,
        api_link_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.TagApiLinkContract:
        """Adds an API to the specified tag via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param api_link_id: Tag-API link identifier. Must be unique in the current API Management
         service instance. Required.
        :type api_link_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: TagApiLinkContract. The TagApiLinkContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagApiLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        tag_id: str,
        api_link_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.TagApiLinkContract:
        """Adds an API to the specified tag via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param api_link_id: Tag-API link identifier. Must be unique in the current API Management
         service instance. Required.
        :type api_link_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: TagApiLinkContract. The TagApiLinkContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagApiLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        tag_id: str,
        api_link_id: str,
        parameters: Union[_models.TagApiLinkContract, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.TagApiLinkContract:
        """Adds an API to the specified tag via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param api_link_id: Tag-API link identifier. Must be unique in the current API Management
         service instance. Required.
        :type api_link_id: str
        :param parameters: Create or update parameters. Is one of the following types:
         TagApiLinkContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.TagApiLinkContract or JSON or IO[bytes]
        :return: TagApiLinkContract. The TagApiLinkContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagApiLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.TagApiLinkContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_tag_api_link_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            tag_id=tag_id,
            api_link_id=api_link_id,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.TagApiLinkContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        tag_id: str,
        api_link_id: str,
        **kwargs: Any
    ) -> None:
        """Deletes the specified API from the specified tag.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param api_link_id: Tag-API link identifier. Must be unique in the current API Management
         service instance. Required.
        :type api_link_id: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_tag_api_link_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            tag_id=tag_id,
            api_link_id=api_link_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_product(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        tag_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.TagApiLinkContract"]:
        """Lists a collection of the API links associated with a tag.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| apiId |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of TagApiLinkContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.TagApiLinkContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.TagApiLinkContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_workspace_tag_api_link_list_by_product_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    workspace_id=workspace_id,
                    tag_id=tag_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.TagApiLinkContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class WorkspaceTagOperationLinkOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`workspace_tag_operation_link` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        tag_id: str,
        operation_link_id: str,
        **kwargs: Any
    ) -> _models.TagOperationLinkContract:
        """Gets the operation link for the tag.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param operation_link_id: Tag-operation link identifier. Must be unique in the current API
         Management service instance. Required.
        :type operation_link_id: str
        :return: TagOperationLinkContract. The TagOperationLinkContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagOperationLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.TagOperationLinkContract] = kwargs.pop("cls", None)

        _request = build_workspace_tag_operation_link_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            tag_id=tag_id,
            operation_link_id=operation_link_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.TagOperationLinkContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        tag_id: str,
        operation_link_id: str,
        parameters: _models.TagOperationLinkContract,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.TagOperationLinkContract:
        """Adds an operation to the specified tag via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param operation_link_id: Tag-operation link identifier. Must be unique in the current API
         Management service instance. Required.
        :type operation_link_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.TagOperationLinkContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: TagOperationLinkContract. The TagOperationLinkContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagOperationLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        tag_id: str,
        operation_link_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.TagOperationLinkContract:
        """Adds an operation to the specified tag via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param operation_link_id: Tag-operation link identifier. Must be unique in the current API
         Management service instance. Required.
        :type operation_link_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: TagOperationLinkContract. The TagOperationLinkContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagOperationLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        tag_id: str,
        operation_link_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.TagOperationLinkContract:
        """Adds an operation to the specified tag via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param operation_link_id: Tag-operation link identifier. Must be unique in the current API
         Management service instance. Required.
        :type operation_link_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: TagOperationLinkContract. The TagOperationLinkContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagOperationLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        tag_id: str,
        operation_link_id: str,
        parameters: Union[_models.TagOperationLinkContract, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.TagOperationLinkContract:
        """Adds an operation to the specified tag via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param operation_link_id: Tag-operation link identifier. Must be unique in the current API
         Management service instance. Required.
        :type operation_link_id: str
        :param parameters: Create or update parameters. Is one of the following types:
         TagOperationLinkContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.TagOperationLinkContract or JSON or
         IO[bytes]
        :return: TagOperationLinkContract. The TagOperationLinkContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagOperationLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.TagOperationLinkContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_tag_operation_link_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            tag_id=tag_id,
            operation_link_id=operation_link_id,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.TagOperationLinkContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        tag_id: str,
        operation_link_id: str,
        **kwargs: Any
    ) -> None:
        """Deletes the specified operation from the specified tag.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param operation_link_id: Tag-operation link identifier. Must be unique in the current API
         Management service instance. Required.
        :type operation_link_id: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_tag_operation_link_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            tag_id=tag_id,
            operation_link_id=operation_link_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_product(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        tag_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.TagOperationLinkContract"]:
        """Lists a collection of the operation links associated with a tag.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| operationId
         | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of TagOperationLinkContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.TagOperationLinkContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.TagOperationLinkContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_workspace_tag_operation_link_list_by_product_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    workspace_id=workspace_id,
                    tag_id=tag_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.TagOperationLinkContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class WorkspaceTagProductLinkOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`workspace_tag_product_link` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        tag_id: str,
        product_link_id: str,
        **kwargs: Any
    ) -> _models.TagProductLinkContract:
        """Gets the product link for the tag.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param product_link_id: Tag-product link identifier. Must be unique in the current API
         Management service instance. Required.
        :type product_link_id: str
        :return: TagProductLinkContract. The TagProductLinkContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagProductLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.TagProductLinkContract] = kwargs.pop("cls", None)

        _request = build_workspace_tag_product_link_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            tag_id=tag_id,
            product_link_id=product_link_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.TagProductLinkContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        tag_id: str,
        product_link_id: str,
        parameters: _models.TagProductLinkContract,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.TagProductLinkContract:
        """Adds a product to the specified tag via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param product_link_id: Tag-product link identifier. Must be unique in the current API
         Management service instance. Required.
        :type product_link_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.TagProductLinkContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: TagProductLinkContract. The TagProductLinkContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagProductLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        tag_id: str,
        product_link_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.TagProductLinkContract:
        """Adds a product to the specified tag via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param product_link_id: Tag-product link identifier. Must be unique in the current API
         Management service instance. Required.
        :type product_link_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: TagProductLinkContract. The TagProductLinkContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagProductLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        tag_id: str,
        product_link_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.TagProductLinkContract:
        """Adds a product to the specified tag via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param product_link_id: Tag-product link identifier. Must be unique in the current API
         Management service instance. Required.
        :type product_link_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: TagProductLinkContract. The TagProductLinkContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagProductLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        tag_id: str,
        product_link_id: str,
        parameters: Union[_models.TagProductLinkContract, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.TagProductLinkContract:
        """Adds a product to the specified tag via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param product_link_id: Tag-product link identifier. Must be unique in the current API
         Management service instance. Required.
        :type product_link_id: str
        :param parameters: Create or update parameters. Is one of the following types:
         TagProductLinkContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.TagProductLinkContract or JSON or IO[bytes]
        :return: TagProductLinkContract. The TagProductLinkContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagProductLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.TagProductLinkContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_tag_product_link_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            tag_id=tag_id,
            product_link_id=product_link_id,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.TagProductLinkContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        tag_id: str,
        product_link_id: str,
        **kwargs: Any
    ) -> None:
        """Deletes the specified product from the specified tag.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param product_link_id: Tag-product link identifier. Must be unique in the current API
         Management service instance. Required.
        :type product_link_id: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_tag_product_link_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            tag_id=tag_id,
            product_link_id=product_link_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_product(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        tag_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.TagProductLinkContract"]:
        """Lists a collection of the product links associated with a tag.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| productId |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of TagProductLinkContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.TagProductLinkContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.TagProductLinkContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_workspace_tag_product_link_list_by_product_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    workspace_id=workspace_id,
                    tag_id=tag_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.TagProductLinkContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class ApiManagementOperationsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`api_management_operations` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list(self, **kwargs: Any) -> AsyncItemPaged["_models.Operation"]:
        """Lists all of the available REST API operations of the Microsoft.ApiManagement provider.

        :return: An iterator like instance of Operation
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.Operation]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.Operation]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_api_management_operations_list_request(
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.Operation],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class ApiGatewayOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`api_gateway` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, gateway_name: str, **kwargs: Any
    ) -> _models.ApiManagementGatewayResource:
        """Gets an API Management gateway resource description.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param gateway_name: The name of the API Management gateway. Required.
        :type gateway_name: str
        :return: ApiManagementGatewayResource. The ApiManagementGatewayResource is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiManagementGatewayResource
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ApiManagementGatewayResource] = kwargs.pop("cls", None)

        _request = build_api_gateway_get_request(
            resource_group_name=resource_group_name,
            gateway_name=gateway_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ApiManagementGatewayResource, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    async def _create_or_update_initial(
        self,
        resource_group_name: str,
        gateway_name: str,
        parameters: Union[_models.ApiManagementGatewayResource, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_api_gateway_create_or_update_request(
            resource_group_name=resource_group_name,
            gateway_name=gateway_name,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 201:
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        gateway_name: str,
        parameters: _models.ApiManagementGatewayResource,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementGatewayResource]:
        """Creates or updates an API Management gateway. This is long running operation and could take
        several minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param gateway_name: The name of the API Management gateway. Required.
        :type gateway_name: str
        :param parameters: Parameters supplied to the CreateOrUpdate API Management gateway operation.
         Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiManagementGatewayResource
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns ApiManagementGatewayResource. The
         ApiManagementGatewayResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementGatewayResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        gateway_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementGatewayResource]:
        """Creates or updates an API Management gateway. This is long running operation and could take
        several minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param gateway_name: The name of the API Management gateway. Required.
        :type gateway_name: str
        :param parameters: Parameters supplied to the CreateOrUpdate API Management gateway operation.
         Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns ApiManagementGatewayResource. The
         ApiManagementGatewayResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementGatewayResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        gateway_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementGatewayResource]:
        """Creates or updates an API Management gateway. This is long running operation and could take
        several minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param gateway_name: The name of the API Management gateway. Required.
        :type gateway_name: str
        :param parameters: Parameters supplied to the CreateOrUpdate API Management gateway operation.
         Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns ApiManagementGatewayResource. The
         ApiManagementGatewayResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementGatewayResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        gateway_name: str,
        parameters: Union[_models.ApiManagementGatewayResource, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementGatewayResource]:
        """Creates or updates an API Management gateway. This is long running operation and could take
        several minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param gateway_name: The name of the API Management gateway. Required.
        :type gateway_name: str
        :param parameters: Parameters supplied to the CreateOrUpdate API Management gateway operation.
         Is one of the following types: ApiManagementGatewayResource, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiManagementGatewayResource or JSON or
         IO[bytes]
        :return: An instance of AsyncLROPoller that returns ApiManagementGatewayResource. The
         ApiManagementGatewayResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementGatewayResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ApiManagementGatewayResource] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._create_or_update_initial(
                resource_group_name=resource_group_name,
                gateway_name=gateway_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.ApiManagementGatewayResource, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.ApiManagementGatewayResource].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.ApiManagementGatewayResource](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _update_initial(
        self,
        resource_group_name: str,
        gateway_name: str,
        parameters: Union[_models.ApiManagementGatewayUpdateParameters, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_api_gateway_update_request(
            resource_group_name=resource_group_name,
            gateway_name=gateway_name,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_update(
        self,
        resource_group_name: str,
        gateway_name: str,
        parameters: _models.ApiManagementGatewayUpdateParameters,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementGatewayResource]:
        """Updates an existing API Management gateway.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param gateway_name: The name of the API Management gateway. Required.
        :type gateway_name: str
        :param parameters: Parameters supplied to the CreateOrUpdate API Management gateway operation.
         Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiManagementGatewayUpdateParameters
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns ApiManagementGatewayResource. The
         ApiManagementGatewayResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementGatewayResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_update(
        self,
        resource_group_name: str,
        gateway_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementGatewayResource]:
        """Updates an existing API Management gateway.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param gateway_name: The name of the API Management gateway. Required.
        :type gateway_name: str
        :param parameters: Parameters supplied to the CreateOrUpdate API Management gateway operation.
         Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns ApiManagementGatewayResource. The
         ApiManagementGatewayResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementGatewayResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_update(
        self,
        resource_group_name: str,
        gateway_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementGatewayResource]:
        """Updates an existing API Management gateway.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param gateway_name: The name of the API Management gateway. Required.
        :type gateway_name: str
        :param parameters: Parameters supplied to the CreateOrUpdate API Management gateway operation.
         Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns ApiManagementGatewayResource. The
         ApiManagementGatewayResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementGatewayResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_update(
        self,
        resource_group_name: str,
        gateway_name: str,
        parameters: Union[_models.ApiManagementGatewayUpdateParameters, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementGatewayResource]:
        """Updates an existing API Management gateway.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param gateway_name: The name of the API Management gateway. Required.
        :type gateway_name: str
        :param parameters: Parameters supplied to the CreateOrUpdate API Management gateway operation.
         Is one of the following types: ApiManagementGatewayUpdateParameters, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiManagementGatewayUpdateParameters or JSON
         or IO[bytes]
        :return: An instance of AsyncLROPoller that returns ApiManagementGatewayResource. The
         ApiManagementGatewayResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementGatewayResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ApiManagementGatewayResource] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._update_initial(
                resource_group_name=resource_group_name,
                gateway_name=gateway_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.ApiManagementGatewayResource, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.ApiManagementGatewayResource].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.ApiManagementGatewayResource](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _delete_initial(self, resource_group_name: str, gateway_name: str, **kwargs: Any) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        _request = build_api_gateway_delete_request(
            resource_group_name=resource_group_name,
            gateway_name=gateway_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [202, 204]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def begin_delete(
        self, resource_group_name: str, gateway_name: str, **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementGatewayResource]:
        """Deletes an existing API Management gateway.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param gateway_name: The name of the API Management gateway. Required.
        :type gateway_name: str
        :return: An instance of AsyncLROPoller that returns ApiManagementGatewayResource. The
         ApiManagementGatewayResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementGatewayResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ApiManagementGatewayResource] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._delete_initial(
                resource_group_name=resource_group_name,
                gateway_name=gateway_name,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response_headers = {}
            response = pipeline_response.http_response
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))

            deserialized = _deserialize(_models.ApiManagementGatewayResource, response.json())
            if cls:
                return cls(pipeline_response, deserialized, response_headers)  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.ApiManagementGatewayResource].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.ApiManagementGatewayResource](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @distributed_trace
    def list_by_resource_group(
        self, resource_group_name: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.ApiManagementGatewayResource"]:
        """List all API Management gateways within a resource group.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :return: An iterator like instance of ApiManagementGatewayResource
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ApiManagementGatewayResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ApiManagementGatewayResource]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_api_gateway_list_by_resource_group_request(
                    resource_group_name=resource_group_name,
                    subscription_id=self._config.subscription_id,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ApiManagementGatewayResource],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list(self, **kwargs: Any) -> AsyncItemPaged["_models.ApiManagementGatewayResource"]:
        """List all API Management gateways within a subscription.

        :return: An iterator like instance of ApiManagementGatewayResource
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ApiManagementGatewayResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ApiManagementGatewayResource]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_api_gateway_list_request(
                    subscription_id=self._config.subscription_id,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ApiManagementGatewayResource],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class ApiManagementGatewaySkusOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`api_management_gateway_skus` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list_available_skus(
        self, resource_group_name: str, gateway_name: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.GatewayResourceSkuResult"]:
        """Gets available SKUs for API Management gateway.

        Gets all available SKU for a given API Management gateway.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param gateway_name: The name of the API Management gateway. Required.
        :type gateway_name: str
        :return: An iterator like instance of GatewayResourceSkuResult
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.GatewayResourceSkuResult]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.GatewayResourceSkuResult]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_api_management_gateway_skus_list_available_skus_request(
                    resource_group_name=resource_group_name,
                    gateway_name=gateway_name,
                    subscription_id=self._config.subscription_id,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.GatewayResourceSkuResult],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class ApiOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`api` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(self, resource_group_name: str, service_name: str, api_id: str, **kwargs: Any) -> _models.ApiContract:
        """Gets the details of the API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :return: ApiContract. The ApiContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ApiContract] = kwargs.pop("cls", None)

        _request = build_api_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ApiContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(self, resource_group_name: str, service_name: str, api_id: str, **kwargs: Any) -> bool:
        """Gets the entity state (Etag) version of the API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_api_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    async def _create_or_update_initial(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        parameters: Union[_models.ApiCreateOrUpdateParameter, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_api_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["Azure-AsyncOperation"] = self._deserialize(
            "str", response.headers.get("Azure-AsyncOperation")
        )
        response_headers["location"] = self._deserialize("str", response.headers.get("location"))
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        parameters: _models.ApiCreateOrUpdateParameter,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiContract]:
        """Creates new or updates existing specified API of the API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiCreateOrUpdateParameter
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns ApiContract. The ApiContract is compatible
         with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiContract]:
        """Creates new or updates existing specified API of the API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns ApiContract. The ApiContract is compatible
         with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiContract]:
        """Creates new or updates existing specified API of the API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns ApiContract. The ApiContract is compatible
         with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        parameters: Union[_models.ApiCreateOrUpdateParameter, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiContract]:
        """Creates new or updates existing specified API of the API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param parameters: Create or update parameters. Is one of the following types:
         ApiCreateOrUpdateParameter, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiCreateOrUpdateParameter or JSON or
         IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns ApiContract. The ApiContract is compatible
         with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ApiContract] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._create_or_update_initial(
                resource_group_name=resource_group_name,
                service_name=service_name,
                api_id=api_id,
                parameters=parameters,
                etag=etag,
                match_condition=match_condition,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response_headers = {}
            response = pipeline_response.http_response
            response_headers["Azure-AsyncOperation"] = self._deserialize(
                "str", response.headers.get("Azure-AsyncOperation")
            )
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

            deserialized = _deserialize(_models.ApiContract, response.json())
            if cls:
                return cls(pipeline_response, deserialized, response_headers)  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.ApiContract].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.ApiContract](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        parameters: _models.ApiUpdateContract,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ApiContract:
        """Updates the specified API of the API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param parameters: API Update Contract parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiUpdateContract
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ApiContract. The ApiContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ApiContract:
        """Updates the specified API of the API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param parameters: API Update Contract parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ApiContract. The ApiContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ApiContract:
        """Updates the specified API of the API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param parameters: API Update Contract parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ApiContract. The ApiContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        parameters: Union[_models.ApiUpdateContract, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.ApiContract:
        """Updates the specified API of the API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param parameters: API Update Contract parameters. Is one of the following types:
         ApiUpdateContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiUpdateContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ApiContract. The ApiContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ApiContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_api_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ApiContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    async def _delete_initial(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        delete_revisions: Optional[bool] = None,
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        _request = build_api_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            delete_revisions=delete_revisions,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [202, 204]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Azure-AsyncOperation"] = self._deserialize(
                "str", response.headers.get("Azure-AsyncOperation")
            )
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def begin_delete(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        delete_revisions: Optional[bool] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[None]:
        """Deletes the specified API of the API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword delete_revisions: Delete all revisions of the Api. Default value is None.
        :paramtype delete_revisions: bool
        :return: An instance of AsyncLROPoller that returns None
        :rtype: ~azure.core.polling.AsyncLROPoller[None]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._delete_initial(
                resource_group_name=resource_group_name,
                service_name=service_name,
                api_id=api_id,
                etag=etag,
                match_condition=match_condition,
                delete_revisions=delete_revisions,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):  # pylint: disable=inconsistent-return-statements
            if cls:
                return cls(pipeline_response, None, {})  # type: ignore

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[None].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method)  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        tags: Optional[str] = None,
        expand_api_version_set: Optional[bool] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.ApiContract"]:
        """Lists all APIs of the API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         displayName | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>| description | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
         endswith |</br>| serviceUrl | filter | ge, le, eq, ne, gt, lt | substringof, contains,
         startswith, endswith |</br>| path | filter | ge, le, eq, ne, gt, lt | substringof, contains,
         startswith, endswith |</br>| isCurrent | filter | eq, ne |  |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :keyword tags: Include tags in the response. Default value is None.
        :paramtype tags: str
        :keyword expand_api_version_set: Include full ApiVersionSet resource in response. Default value
         is None.
        :paramtype expand_api_version_set: bool
        :return: An iterator like instance of ApiContract
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ApiContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ApiContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_api_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    tags=tags,
                    expand_api_version_set=expand_api_version_set,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ApiContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list_by_tags(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        include_not_tagged_apis: Optional[bool] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.TagResourceContract"]:
        """Lists a collection of apis associated with tags.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         displayName | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>| apiRevision | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
         endswith |</br>| path | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
         endswith |</br>| description | filter | ge, le, eq, ne, gt, lt | substringof, contains,
         startswith, endswith |</br>| serviceUrl | filter | ge, le, eq, ne, gt, lt | substringof,
         contains, startswith, endswith |</br>| isCurrent | filter | eq |     |</br>. Default value is
         None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :keyword include_not_tagged_apis: Include not tagged APIs. Default value is None.
        :paramtype include_not_tagged_apis: bool
        :return: An iterator like instance of TagResourceContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.TagResourceContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.TagResourceContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_api_list_by_tags_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    include_not_tagged_apis=include_not_tagged_apis,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.TagResourceContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class ApiRevisionOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`api_revision` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.ApiRevisionContract"]:
        """Lists all revisions of an API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| apiRevision
         | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of ApiRevisionContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ApiRevisionContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ApiRevisionContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_api_revision_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    api_id=api_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ApiRevisionContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class ApiProductOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`api_product` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list_by_apis(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.ProductContract"]:
        """Lists all Products, which the API is part of.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| displayName
         | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of ProductContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ProductContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ProductContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_api_product_list_by_apis_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    api_id=api_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ProductContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class OperationOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`operation` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list_by_tags(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        include_not_tagged_operations: Optional[bool] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.TagResourceContract"]:
        """Lists a collection of operations associated with tags.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         displayName | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>| apiName | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>| description | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
         endswith |</br>| method | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
         endswith |</br>| urlTemplate | filter | ge, le, eq, ne, gt, lt | substringof, contains,
         startswith, endswith |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :keyword include_not_tagged_operations: Include not tagged Operations. Default value is None.
        :paramtype include_not_tagged_operations: bool
        :return: An iterator like instance of TagResourceContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.TagResourceContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.TagResourceContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_operation_list_by_tags_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    api_id=api_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    include_not_tagged_operations=include_not_tagged_operations,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.TagResourceContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class WorkspaceApiRevisionOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`workspace_api_revision` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.ApiRevisionContract"]:
        """Lists all revisions of an API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| apiRevision
         | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of ApiRevisionContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ApiRevisionContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ApiRevisionContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_workspace_api_revision_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    workspace_id=workspace_id,
                    api_id=api_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ApiRevisionContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class ApiManagementServiceOperations:  # pylint: disable=too-many-public-methods
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`api_management_service` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, **kwargs: Any
    ) -> _models.ApiManagementServiceResource:
        """Gets an API Management service resource description.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :return: ApiManagementServiceResource. The ApiManagementServiceResource is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiManagementServiceResource
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ApiManagementServiceResource] = kwargs.pop("cls", None)

        _request = build_api_management_service_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ApiManagementServiceResource, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    async def _create_or_update_initial(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: Union[_models.ApiManagementServiceResource, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_api_management_service_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 201:
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: _models.ApiManagementServiceResource,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementServiceResource]:
        """Creates or updates an API Management service. This is long running operation and could take
        several minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Parameters supplied to the CreateOrUpdate API Management service operation.
         Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiManagementServiceResource
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns ApiManagementServiceResource. The
         ApiManagementServiceResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementServiceResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementServiceResource]:
        """Creates or updates an API Management service. This is long running operation and could take
        several minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Parameters supplied to the CreateOrUpdate API Management service operation.
         Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns ApiManagementServiceResource. The
         ApiManagementServiceResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementServiceResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementServiceResource]:
        """Creates or updates an API Management service. This is long running operation and could take
        several minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Parameters supplied to the CreateOrUpdate API Management service operation.
         Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns ApiManagementServiceResource. The
         ApiManagementServiceResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementServiceResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: Union[_models.ApiManagementServiceResource, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementServiceResource]:
        """Creates or updates an API Management service. This is long running operation and could take
        several minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Parameters supplied to the CreateOrUpdate API Management service operation.
         Is one of the following types: ApiManagementServiceResource, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiManagementServiceResource or JSON or
         IO[bytes]
        :return: An instance of AsyncLROPoller that returns ApiManagementServiceResource. The
         ApiManagementServiceResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementServiceResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ApiManagementServiceResource] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._create_or_update_initial(
                resource_group_name=resource_group_name,
                service_name=service_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.ApiManagementServiceResource, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.ApiManagementServiceResource].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.ApiManagementServiceResource](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _update_initial(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: Union[_models.ApiManagementServiceUpdateParameters, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_api_management_service_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_update(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: _models.ApiManagementServiceUpdateParameters,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementServiceResource]:
        """Updates an existing API Management service.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Parameters supplied to the CreateOrUpdate API Management service operation.
         Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiManagementServiceUpdateParameters
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns ApiManagementServiceResource. The
         ApiManagementServiceResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementServiceResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_update(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementServiceResource]:
        """Updates an existing API Management service.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Parameters supplied to the CreateOrUpdate API Management service operation.
         Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns ApiManagementServiceResource. The
         ApiManagementServiceResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementServiceResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_update(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementServiceResource]:
        """Updates an existing API Management service.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Parameters supplied to the CreateOrUpdate API Management service operation.
         Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns ApiManagementServiceResource. The
         ApiManagementServiceResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementServiceResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_update(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: Union[_models.ApiManagementServiceUpdateParameters, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementServiceResource]:
        """Updates an existing API Management service.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Parameters supplied to the CreateOrUpdate API Management service operation.
         Is one of the following types: ApiManagementServiceUpdateParameters, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiManagementServiceUpdateParameters or JSON
         or IO[bytes]
        :return: An instance of AsyncLROPoller that returns ApiManagementServiceResource. The
         ApiManagementServiceResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementServiceResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ApiManagementServiceResource] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._update_initial(
                resource_group_name=resource_group_name,
                service_name=service_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.ApiManagementServiceResource, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.ApiManagementServiceResource].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.ApiManagementServiceResource](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _delete_initial(self, resource_group_name: str, service_name: str, **kwargs: Any) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        _request = build_api_management_service_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202, 204]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def begin_delete(
        self, resource_group_name: str, service_name: str, **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementServiceResource]:
        """Deletes an existing API Management service.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :return: An instance of AsyncLROPoller that returns ApiManagementServiceResource. The
         ApiManagementServiceResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementServiceResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ApiManagementServiceResource] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._delete_initial(
                resource_group_name=resource_group_name,
                service_name=service_name,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.ApiManagementServiceResource, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.ApiManagementServiceResource].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.ApiManagementServiceResource](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @distributed_trace
    def list_by_resource_group(
        self, resource_group_name: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.ApiManagementServiceResource"]:
        """List all API Management services within a resource group.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :return: An iterator like instance of ApiManagementServiceResource
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ApiManagementServiceResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ApiManagementServiceResource]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_api_management_service_list_by_resource_group_request(
                    resource_group_name=resource_group_name,
                    subscription_id=self._config.subscription_id,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ApiManagementServiceResource],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list(self, **kwargs: Any) -> AsyncItemPaged["_models.ApiManagementServiceResource"]:
        """Lists all API Management services within an Azure subscription.

        :return: An iterator like instance of ApiManagementServiceResource
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ApiManagementServiceResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ApiManagementServiceResource]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_api_management_service_list_request(
                    subscription_id=self._config.subscription_id,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ApiManagementServiceResource],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    async def _restore_initial(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: Union[_models.ApiManagementServiceBackupRestoreParameters, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_api_management_service_restore_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_restore(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: _models.ApiManagementServiceBackupRestoreParameters,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementServiceResource]:
        """Restores a backup of an API Management service created using the ApiManagementService_Backup
        operation on the current service. This is a long running operation and could take several
        minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Parameters supplied to the Restore API Management service from backup
         operation. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiManagementServiceBackupRestoreParameters
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns ApiManagementServiceResource. The
         ApiManagementServiceResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementServiceResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_restore(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementServiceResource]:
        """Restores a backup of an API Management service created using the ApiManagementService_Backup
        operation on the current service. This is a long running operation and could take several
        minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Parameters supplied to the Restore API Management service from backup
         operation. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns ApiManagementServiceResource. The
         ApiManagementServiceResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementServiceResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_restore(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementServiceResource]:
        """Restores a backup of an API Management service created using the ApiManagementService_Backup
        operation on the current service. This is a long running operation and could take several
        minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Parameters supplied to the Restore API Management service from backup
         operation. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns ApiManagementServiceResource. The
         ApiManagementServiceResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementServiceResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_restore(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: Union[_models.ApiManagementServiceBackupRestoreParameters, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementServiceResource]:
        """Restores a backup of an API Management service created using the ApiManagementService_Backup
        operation on the current service. This is a long running operation and could take several
        minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Parameters supplied to the Restore API Management service from backup
         operation. Is one of the following types: ApiManagementServiceBackupRestoreParameters, JSON,
         IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiManagementServiceBackupRestoreParameters
         or JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns ApiManagementServiceResource. The
         ApiManagementServiceResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementServiceResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ApiManagementServiceResource] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._restore_initial(
                resource_group_name=resource_group_name,
                service_name=service_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response_headers = {}
            response = pipeline_response.http_response
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

            deserialized = _deserialize(_models.ApiManagementServiceResource, response.json())
            if cls:
                return cls(pipeline_response, deserialized, response_headers)  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.ApiManagementServiceResource].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.ApiManagementServiceResource](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _backup_initial(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: Union[_models.ApiManagementServiceBackupRestoreParameters, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_api_management_service_backup_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_backup(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: _models.ApiManagementServiceBackupRestoreParameters,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementServiceResource]:
        """Creates a backup of the API Management service to the given Azure Storage Account. This is long
        running operation and could take several minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Parameters supplied to the ApiManagementService_Backup operation. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiManagementServiceBackupRestoreParameters
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns ApiManagementServiceResource. The
         ApiManagementServiceResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementServiceResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_backup(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementServiceResource]:
        """Creates a backup of the API Management service to the given Azure Storage Account. This is long
        running operation and could take several minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Parameters supplied to the ApiManagementService_Backup operation. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns ApiManagementServiceResource. The
         ApiManagementServiceResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementServiceResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_backup(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementServiceResource]:
        """Creates a backup of the API Management service to the given Azure Storage Account. This is long
        running operation and could take several minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Parameters supplied to the ApiManagementService_Backup operation. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns ApiManagementServiceResource. The
         ApiManagementServiceResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementServiceResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_backup(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: Union[_models.ApiManagementServiceBackupRestoreParameters, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementServiceResource]:
        """Creates a backup of the API Management service to the given Azure Storage Account. This is long
        running operation and could take several minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Parameters supplied to the ApiManagementService_Backup operation. Is one of
         the following types: ApiManagementServiceBackupRestoreParameters, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiManagementServiceBackupRestoreParameters
         or JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns ApiManagementServiceResource. The
         ApiManagementServiceResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementServiceResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ApiManagementServiceResource] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._backup_initial(
                resource_group_name=resource_group_name,
                service_name=service_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response_headers = {}
            response = pipeline_response.http_response
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

            deserialized = _deserialize(_models.ApiManagementServiceResource, response.json())
            if cls:
                return cls(pipeline_response, deserialized, response_headers)  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.ApiManagementServiceResource].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.ApiManagementServiceResource](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _migrate_to_stv2_initial(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: Optional[Union[_models.MigrateToStv2Contract, JSON, IO[bytes]]] = None,
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        content_type = content_type if parameters else None
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json" if parameters else None
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            if parameters is not None:
                _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore
            else:
                _content = None

        _request = build_api_management_service_migrate_to_stv2_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_migrate_to_stv2(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: Optional[_models.MigrateToStv2Contract] = None,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementServiceResource]:
        """Upgrades an API Management service to the Stv2 platform. For details refer to
        `https://aka.ms/apim-migrate-stv2 <https://aka.ms/apim-migrate-stv2>`_. This change is not
        reversible. This is long running operation and could take several minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Optional parameters supplied to migrate service. Default value is None.
        :type parameters: ~azure.mgmt.apimanagement.models.MigrateToStv2Contract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns ApiManagementServiceResource. The
         ApiManagementServiceResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementServiceResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_migrate_to_stv2(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: Optional[JSON] = None,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementServiceResource]:
        """Upgrades an API Management service to the Stv2 platform. For details refer to
        `https://aka.ms/apim-migrate-stv2 <https://aka.ms/apim-migrate-stv2>`_. This change is not
        reversible. This is long running operation and could take several minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Optional parameters supplied to migrate service. Default value is None.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns ApiManagementServiceResource. The
         ApiManagementServiceResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementServiceResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_migrate_to_stv2(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: Optional[IO[bytes]] = None,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementServiceResource]:
        """Upgrades an API Management service to the Stv2 platform. For details refer to
        `https://aka.ms/apim-migrate-stv2 <https://aka.ms/apim-migrate-stv2>`_. This change is not
        reversible. This is long running operation and could take several minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Optional parameters supplied to migrate service. Default value is None.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns ApiManagementServiceResource. The
         ApiManagementServiceResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementServiceResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_migrate_to_stv2(
        self,
        resource_group_name: str,
        service_name: str,
        parameters: Optional[Union[_models.MigrateToStv2Contract, JSON, IO[bytes]]] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementServiceResource]:
        """Upgrades an API Management service to the Stv2 platform. For details refer to
        `https://aka.ms/apim-migrate-stv2 <https://aka.ms/apim-migrate-stv2>`_. This change is not
        reversible. This is long running operation and could take several minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Optional parameters supplied to migrate service. Is one of the following
         types: MigrateToStv2Contract, JSON, IO[bytes] Default value is None.
        :type parameters: ~azure.mgmt.apimanagement.models.MigrateToStv2Contract or JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns ApiManagementServiceResource. The
         ApiManagementServiceResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementServiceResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        content_type = content_type if parameters else None
        cls: ClsType[_models.ApiManagementServiceResource] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._migrate_to_stv2_initial(
                resource_group_name=resource_group_name,
                service_name=service_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response_headers = {}
            response = pipeline_response.http_response
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

            deserialized = _deserialize(_models.ApiManagementServiceResource, response.json())
            if cls:
                return cls(pipeline_response, deserialized, response_headers)  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.ApiManagementServiceResource].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.ApiManagementServiceResource](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @distributed_trace_async
    async def get_sso_token(
        self, resource_group_name: str, service_name: str, **kwargs: Any
    ) -> _models.ApiManagementServiceGetSsoTokenResult:
        """Gets the Single-Sign-On token for the API Management Service which is valid for 5 Minutes.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :return: ApiManagementServiceGetSsoTokenResult. The ApiManagementServiceGetSsoTokenResult is
         compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiManagementServiceGetSsoTokenResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ApiManagementServiceGetSsoTokenResult] = kwargs.pop("cls", None)

        _request = build_api_management_service_get_sso_token_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ApiManagementServiceGetSsoTokenResult, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    async def _apply_network_configuration_updates_initial(  # pylint: disable=name-too-long
        self,
        resource_group_name: str,
        service_name: str,
        parameters: Optional[
            Union[_models.ApiManagementServiceApplyNetworkConfigurationParameters, JSON, IO[bytes]]
        ] = None,
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        content_type = content_type if parameters else None
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json" if parameters else None
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            if parameters is not None:
                _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore
            else:
                _content = None

        _request = build_api_management_service_apply_network_configuration_updates_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_apply_network_configuration_updates(  # pylint: disable=name-too-long
        self,
        resource_group_name: str,
        service_name: str,
        parameters: Optional[_models.ApiManagementServiceApplyNetworkConfigurationParameters] = None,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementServiceResource]:
        """Updates the Microsoft.ApiManagement resource running in the Virtual network to pick the updated
        DNS changes.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Parameters supplied to the Apply Network Configuration operation. If the
         parameters are empty, all the regions in which the Api Management service is deployed will be
         updated sequentially without incurring downtime in the region. Default value is None.
        :type parameters:
         ~azure.mgmt.apimanagement.models.ApiManagementServiceApplyNetworkConfigurationParameters
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns ApiManagementServiceResource. The
         ApiManagementServiceResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementServiceResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_apply_network_configuration_updates(  # pylint: disable=name-too-long
        self,
        resource_group_name: str,
        service_name: str,
        parameters: Optional[JSON] = None,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementServiceResource]:
        """Updates the Microsoft.ApiManagement resource running in the Virtual network to pick the updated
        DNS changes.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Parameters supplied to the Apply Network Configuration operation. If the
         parameters are empty, all the regions in which the Api Management service is deployed will be
         updated sequentially without incurring downtime in the region. Default value is None.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns ApiManagementServiceResource. The
         ApiManagementServiceResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementServiceResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_apply_network_configuration_updates(  # pylint: disable=name-too-long
        self,
        resource_group_name: str,
        service_name: str,
        parameters: Optional[IO[bytes]] = None,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementServiceResource]:
        """Updates the Microsoft.ApiManagement resource running in the Virtual network to pick the updated
        DNS changes.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Parameters supplied to the Apply Network Configuration operation. If the
         parameters are empty, all the regions in which the Api Management service is deployed will be
         updated sequentially without incurring downtime in the region. Default value is None.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns ApiManagementServiceResource. The
         ApiManagementServiceResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementServiceResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_apply_network_configuration_updates(  # pylint: disable=name-too-long
        self,
        resource_group_name: str,
        service_name: str,
        parameters: Optional[
            Union[_models.ApiManagementServiceApplyNetworkConfigurationParameters, JSON, IO[bytes]]
        ] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementServiceResource]:
        """Updates the Microsoft.ApiManagement resource running in the Virtual network to pick the updated
        DNS changes.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param parameters: Parameters supplied to the Apply Network Configuration operation. If the
         parameters are empty, all the regions in which the Api Management service is deployed will be
         updated sequentially without incurring downtime in the region. Is one of the following types:
         ApiManagementServiceApplyNetworkConfigurationParameters, JSON, IO[bytes] Default value is None.
        :type parameters:
         ~azure.mgmt.apimanagement.models.ApiManagementServiceApplyNetworkConfigurationParameters or
         JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns ApiManagementServiceResource. The
         ApiManagementServiceResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementServiceResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        content_type = content_type if parameters else None
        cls: ClsType[_models.ApiManagementServiceResource] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._apply_network_configuration_updates_initial(
                resource_group_name=resource_group_name,
                service_name=service_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response_headers = {}
            response = pipeline_response.http_response
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

            deserialized = _deserialize(_models.ApiManagementServiceResource, response.json())
            if cls:
                return cls(pipeline_response, deserialized, response_headers)  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.ApiManagementServiceResource].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.ApiManagementServiceResource](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _refresh_hostnames_initial(
        self, resource_group_name: str, service_name: str, **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        _request = build_api_management_service_refresh_hostnames_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def begin_refresh_hostnames(
        self, resource_group_name: str, service_name: str, **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementServiceResource]:
        """Force Refresh the SSL certificate attached to the Custom Hostnames configured using secret from
        KeyVault on the Api Management service.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :return: An instance of AsyncLROPoller that returns ApiManagementServiceResource. The
         ApiManagementServiceResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementServiceResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ApiManagementServiceResource] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._refresh_hostnames_initial(
                resource_group_name=resource_group_name,
                service_name=service_name,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response_headers = {}
            response = pipeline_response.http_response
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

            deserialized = _deserialize(_models.ApiManagementServiceResource, response.json())
            if cls:
                return cls(pipeline_response, deserialized, response_headers)  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.ApiManagementServiceResource].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.ApiManagementServiceResource](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @overload
    async def check_name_availability(
        self,
        parameters: _models.ApiManagementServiceCheckNameAvailabilityParameters,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ApiManagementServiceNameAvailabilityResult:
        """Checks availability and correctness of a name for an API Management service.

        :param parameters: The request body. Required.
        :type parameters:
         ~azure.mgmt.apimanagement.models.ApiManagementServiceCheckNameAvailabilityParameters
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ApiManagementServiceNameAvailabilityResult. The
         ApiManagementServiceNameAvailabilityResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiManagementServiceNameAvailabilityResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def check_name_availability(
        self, parameters: JSON, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.ApiManagementServiceNameAvailabilityResult:
        """Checks availability and correctness of a name for an API Management service.

        :param parameters: The request body. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ApiManagementServiceNameAvailabilityResult. The
         ApiManagementServiceNameAvailabilityResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiManagementServiceNameAvailabilityResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def check_name_availability(
        self, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.ApiManagementServiceNameAvailabilityResult:
        """Checks availability and correctness of a name for an API Management service.

        :param parameters: The request body. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ApiManagementServiceNameAvailabilityResult. The
         ApiManagementServiceNameAvailabilityResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiManagementServiceNameAvailabilityResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def check_name_availability(
        self,
        parameters: Union[_models.ApiManagementServiceCheckNameAvailabilityParameters, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.ApiManagementServiceNameAvailabilityResult:
        """Checks availability and correctness of a name for an API Management service.

        :param parameters: The request body. Is one of the following types:
         ApiManagementServiceCheckNameAvailabilityParameters, JSON, IO[bytes] Required.
        :type parameters:
         ~azure.mgmt.apimanagement.models.ApiManagementServiceCheckNameAvailabilityParameters or JSON or
         IO[bytes]
        :return: ApiManagementServiceNameAvailabilityResult. The
         ApiManagementServiceNameAvailabilityResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiManagementServiceNameAvailabilityResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ApiManagementServiceNameAvailabilityResult] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_api_management_service_check_name_availability_request(
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ApiManagementServiceNameAvailabilityResult, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_domain_ownership_identifier(
        self, **kwargs: Any
    ) -> _models.ApiManagementServiceGetDomainOwnershipIdentifierResult:
        """Get the custom domain ownership identifier for an API Management service.

        :return: ApiManagementServiceGetDomainOwnershipIdentifierResult. The
         ApiManagementServiceGetDomainOwnershipIdentifierResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiManagementServiceGetDomainOwnershipIdentifierResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ApiManagementServiceGetDomainOwnershipIdentifierResult] = kwargs.pop("cls", None)

        _request = build_api_management_service_get_domain_ownership_identifier_request(
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ApiManagementServiceGetDomainOwnershipIdentifierResult, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class AllPoliciesOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`all_policies` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list_by_service(
        self, resource_group_name: str, service_name: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.AllPoliciesContract"]:
        """Status of all policies of API Management services.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :return: An iterator like instance of AllPoliciesContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.AllPoliciesContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.AllPoliciesContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_all_policies_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.AllPoliciesContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class ApiManagementServiceSkusOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`api_management_service_skus` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list_available_service_skus(
        self, resource_group_name: str, service_name: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.ResourceSkuResult"]:
        """Gets all available SKU for a given API Management service.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :return: An iterator like instance of ResourceSkuResult
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ResourceSkuResult]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ResourceSkuResult]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_api_management_service_skus_list_available_service_skus_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ResourceSkuResult],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class NetworkStatusOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`network_status` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def list_by_service(
        self, resource_group_name: str, service_name: str, **kwargs: Any
    ) -> List[_models.NetworkStatusContractByLocation]:
        """Gets the Connectivity Status to the external resources on which the Api Management service
        depends from inside the Cloud Service. This also returns the DNS Servers as visible to the
        CloudService.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :return: list of NetworkStatusContractByLocation
        :rtype: list[~azure.mgmt.apimanagement.models.NetworkStatusContractByLocation]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.NetworkStatusContractByLocation]] = kwargs.pop("cls", None)

        _request = build_network_status_list_by_service_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(List[_models.NetworkStatusContractByLocation], response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def list_by_location(
        self, resource_group_name: str, service_name: str, location_name: str, **kwargs: Any
    ) -> _models.NetworkStatusContract:
        """Gets the Connectivity Status to the external resources on which the Api Management service
        depends from inside the Cloud Service. This also returns the DNS Servers as visible to the
        CloudService.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param location_name: Location in which the API Management service is deployed. This is one of
         the Azure Regions like West US, East US, South Central US. Required.
        :type location_name: str
        :return: NetworkStatusContract. The NetworkStatusContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.NetworkStatusContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.NetworkStatusContract] = kwargs.pop("cls", None)

        _request = build_network_status_list_by_location_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            location_name=location_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.NetworkStatusContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class OutboundNetworkDependenciesEndpointsOperations:  # pylint: disable=name-too-long
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`outbound_network_dependencies_endpoints` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def list_by_service(
        self, resource_group_name: str, service_name: str, **kwargs: Any
    ) -> _models.OutboundEnvironmentEndpointList:
        """Gets the network endpoints of all outbound dependencies of a ApiManagement service.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :return: OutboundEnvironmentEndpointList. The OutboundEnvironmentEndpointList is compatible
         with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.OutboundEnvironmentEndpointList
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.OutboundEnvironmentEndpointList] = kwargs.pop("cls", None)

        _request = build_outbound_network_dependencies_endpoints_list_by_service_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.OutboundEnvironmentEndpointList, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class PolicyDescriptionOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`policy_description` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        scope: Optional[Union[str, _models.PolicyScopeContract]] = None,
        **kwargs: Any
    ) -> _models.PolicyDescriptionCollection:
        """Lists all policy descriptions.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword scope: Policy scope. Known values are: "Tenant", "Product", "Api", "Operation", and
         "All". Default value is None.
        :paramtype scope: str or ~azure.mgmt.apimanagement.models.PolicyScopeContract
        :return: PolicyDescriptionCollection. The PolicyDescriptionCollection is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyDescriptionCollection
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.PolicyDescriptionCollection] = kwargs.pop("cls", None)

        _request = build_policy_description_list_by_service_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            subscription_id=self._config.subscription_id,
            scope=scope,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PolicyDescriptionCollection, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class PolicyRestrictionValidationsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`policy_restriction_validations` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    async def _by_service_initial(
        self, resource_group_name: str, service_name: str, **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        _request = build_policy_restriction_validations_by_service_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def begin_by_service(
        self, resource_group_name: str, service_name: str, **kwargs: Any
    ) -> AsyncLROPoller[_models.OperationResultContract]:
        """Validate all policies of API Management services.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :return: An instance of AsyncLROPoller that returns OperationResultContract. The
         OperationResultContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.OperationResultContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.OperationResultContract] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._by_service_initial(
                resource_group_name=resource_group_name,
                service_name=service_name,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response_headers = {}
            response = pipeline_response.http_response
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

            deserialized = _deserialize(_models.OperationResultContract, response.json())
            if cls:
                return cls(pipeline_response, deserialized, response_headers)  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.OperationResultContract].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.OperationResultContract](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )


class PortalSettingsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`portal_settings` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def list_by_service(
        self, resource_group_name: str, service_name: str, **kwargs: Any
    ) -> _models.PortalSettingsCollection:
        """Lists a collection of portalsettings defined within a service instance..

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :return: PortalSettingsCollection. The PortalSettingsCollection is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PortalSettingsCollection
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.PortalSettingsCollection] = kwargs.pop("cls", None)

        _request = build_portal_settings_list_by_service_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PortalSettingsCollection, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class ProductOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`product` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list_by_tags(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        include_not_tagged_products: Optional[bool] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.TagResourceContract"]:
        """Lists a collection of products associated with tags.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         displayName | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>| description | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
         endswith |</br>| terms | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
         endswith |</br>| state | filter | eq | substringof, contains, startswith, endswith |</br>.
         Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :keyword include_not_tagged_products: Include not tagged Products. Default value is None.
        :paramtype include_not_tagged_products: bool
        :return: An iterator like instance of TagResourceContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.TagResourceContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.TagResourceContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_product_list_by_tags_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    include_not_tagged_products=include_not_tagged_products,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.TagResourceContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, product_id: str, **kwargs: Any
    ) -> _models.ProductContract:
        """Gets the details of the product specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :return: ProductContract. The ProductContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ProductContract] = kwargs.pop("cls", None)

        _request = build_product_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            product_id=product_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ProductContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(self, resource_group_name: str, service_name: str, product_id: str, **kwargs: Any) -> bool:
        """Gets the entity state (Etag) version of the product specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_product_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            product_id=product_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        parameters: _models.ProductContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ProductContract:
        """Creates or Updates a product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ProductContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ProductContract. The ProductContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ProductContract:
        """Creates or Updates a product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ProductContract. The ProductContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ProductContract:
        """Creates or Updates a product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ProductContract. The ProductContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        parameters: Union[_models.ProductContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ProductContract:
        """Creates or Updates a product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param parameters: Create or update parameters. Is one of the following types: ProductContract,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ProductContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ProductContract. The ProductContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ProductContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_product_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            product_id=product_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ProductContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        parameters: _models.ProductUpdateParameters,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ProductContract:
        """Update existing product details.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param parameters: Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ProductUpdateParameters
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ProductContract. The ProductContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ProductContract:
        """Update existing product details.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param parameters: Update parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ProductContract. The ProductContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ProductContract:
        """Update existing product details.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param parameters: Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ProductContract. The ProductContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        parameters: Union[_models.ProductUpdateParameters, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.ProductContract:
        """Update existing product details.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param parameters: Update parameters. Is one of the following types: ProductUpdateParameters,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ProductUpdateParameters or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ProductContract. The ProductContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ProductContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_product_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            product_id=product_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ProductContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        delete_subscriptions: Optional[bool] = None,
        **kwargs: Any
    ) -> None:
        """Delete product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword delete_subscriptions: Delete existing subscriptions associated with the product or
         not. Default value is None.
        :paramtype delete_subscriptions: bool
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_product_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            product_id=product_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            delete_subscriptions=delete_subscriptions,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        expand_groups: Optional[bool] = None,
        tags: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.ProductContract"]:
        """Lists a collection of products in the specified service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         displayName | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>| description | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
         endswith |</br>| terms | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
         endswith |</br>| state | filter | eq |     |</br>| groups | expand |     |     |</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :keyword expand_groups: When set to true, the response contains an array of groups that have
         visibility to the product. The default is false. Default value is None.
        :paramtype expand_groups: bool
        :keyword tags: Products which are part of a specific tag. Default value is None.
        :paramtype tags: str
        :return: An iterator like instance of ProductContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ProductContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ProductContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_product_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    expand_groups=expand_groups,
                    tags=tags,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ProductContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class QuotaByCounterKeysOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`quota_by_counter_keys` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def list_by_service(
        self, resource_group_name: str, service_name: str, quota_counter_key: str, **kwargs: Any
    ) -> _models.QuotaCounterCollection:
        """Lists a collection of current quota counter periods associated with the counter-key configured
        in the policy on the specified service instance. The api does not support paging yet.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param quota_counter_key: Quota counter key identifier. This is the result of expression
         defined in ``counter-key`` attribute of the quota-by-key policy. For example, if you specify
         ``counter-key="boo"`` in the policy, then it’s accessible by ``"boo"`` counter key. But if it’s
         defined as ``counter-key="@("b"+"a")"`` then it will be accessible by ``"ba"`` key. Required.
        :type quota_counter_key: str
        :return: QuotaCounterCollection. The QuotaCounterCollection is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.QuotaCounterCollection
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.QuotaCounterCollection] = kwargs.pop("cls", None)

        _request = build_quota_by_counter_keys_list_by_service_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            quota_counter_key=quota_counter_key,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.QuotaCounterCollection, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        quota_counter_key: str,
        parameters: _models.QuotaCounterValueUpdateContract,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.QuotaCounterCollection:
        """Updates all the quota counter values specified with the existing quota counter key to a value
        in the specified service instance. This should be used for reset of the quota counter values.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param quota_counter_key: Quota counter key identifier. This is the result of expression
         defined in ``counter-key`` attribute of the quota-by-key policy. For example, if you specify
         ``counter-key="boo"`` in the policy, then it’s accessible by ``"boo"`` counter key. But if it’s
         defined as ``counter-key="@("b"+"a")"`` then it will be accessible by ``"ba"`` key. Required.
        :type quota_counter_key: str
        :param parameters: The value of the quota counter to be applied to all quota counter periods.
         Required.
        :type parameters: ~azure.mgmt.apimanagement.models.QuotaCounterValueUpdateContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: QuotaCounterCollection. The QuotaCounterCollection is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.QuotaCounterCollection
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        quota_counter_key: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.QuotaCounterCollection:
        """Updates all the quota counter values specified with the existing quota counter key to a value
        in the specified service instance. This should be used for reset of the quota counter values.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param quota_counter_key: Quota counter key identifier. This is the result of expression
         defined in ``counter-key`` attribute of the quota-by-key policy. For example, if you specify
         ``counter-key="boo"`` in the policy, then it’s accessible by ``"boo"`` counter key. But if it’s
         defined as ``counter-key="@("b"+"a")"`` then it will be accessible by ``"ba"`` key. Required.
        :type quota_counter_key: str
        :param parameters: The value of the quota counter to be applied to all quota counter periods.
         Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: QuotaCounterCollection. The QuotaCounterCollection is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.QuotaCounterCollection
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        quota_counter_key: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.QuotaCounterCollection:
        """Updates all the quota counter values specified with the existing quota counter key to a value
        in the specified service instance. This should be used for reset of the quota counter values.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param quota_counter_key: Quota counter key identifier. This is the result of expression
         defined in ``counter-key`` attribute of the quota-by-key policy. For example, if you specify
         ``counter-key="boo"`` in the policy, then it’s accessible by ``"boo"`` counter key. But if it’s
         defined as ``counter-key="@("b"+"a")"`` then it will be accessible by ``"ba"`` key. Required.
        :type quota_counter_key: str
        :param parameters: The value of the quota counter to be applied to all quota counter periods.
         Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: QuotaCounterCollection. The QuotaCounterCollection is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.QuotaCounterCollection
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        quota_counter_key: str,
        parameters: Union[_models.QuotaCounterValueUpdateContract, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.QuotaCounterCollection:
        """Updates all the quota counter values specified with the existing quota counter key to a value
        in the specified service instance. This should be used for reset of the quota counter values.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param quota_counter_key: Quota counter key identifier. This is the result of expression
         defined in ``counter-key`` attribute of the quota-by-key policy. For example, if you specify
         ``counter-key="boo"`` in the policy, then it’s accessible by ``"boo"`` counter key. But if it’s
         defined as ``counter-key="@("b"+"a")"`` then it will be accessible by ``"ba"`` key. Required.
        :type quota_counter_key: str
        :param parameters: The value of the quota counter to be applied to all quota counter periods.
         Is one of the following types: QuotaCounterValueUpdateContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.QuotaCounterValueUpdateContract or JSON or
         IO[bytes]
        :return: QuotaCounterCollection. The QuotaCounterCollection is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.QuotaCounterCollection
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.QuotaCounterCollection] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_quota_by_counter_keys_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            quota_counter_key=quota_counter_key,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.QuotaCounterCollection, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class QuotaByPeriodKeysOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`quota_by_period_keys` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, quota_counter_key: str, quota_period_key: str, **kwargs: Any
    ) -> _models.QuotaCounterContract:
        """Gets the value of the quota counter associated with the counter-key in the policy for the
        specific period in service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param quota_counter_key: Quota counter key identifier. This is the result of expression
         defined in ``counter-key`` attribute of the quota-by-key policy. For example, if you specify
         ``counter-key="boo"`` in the policy, then it’s accessible by ``"boo"`` counter key. But if it’s
         defined as ``counter-key="@("b"+"a")"`` then it will be accessible by ``"ba"`` key. Required.
        :type quota_counter_key: str
        :param quota_period_key: Quota period key identifier. Required.
        :type quota_period_key: str
        :return: QuotaCounterContract. The QuotaCounterContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.QuotaCounterContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.QuotaCounterContract] = kwargs.pop("cls", None)

        _request = build_quota_by_period_keys_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            quota_counter_key=quota_counter_key,
            quota_period_key=quota_period_key,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.QuotaCounterContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        quota_counter_key: str,
        quota_period_key: str,
        parameters: _models.QuotaCounterValueUpdateContract,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.QuotaCounterContract:
        """Updates an existing quota counter value in the specified service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param quota_counter_key: Quota counter key identifier. This is the result of expression
         defined in ``counter-key`` attribute of the quota-by-key policy. For example, if you specify
         ``counter-key="boo"`` in the policy, then it’s accessible by ``"boo"`` counter key. But if it’s
         defined as ``counter-key="@("b"+"a")"`` then it will be accessible by ``"ba"`` key. Required.
        :type quota_counter_key: str
        :param quota_period_key: Quota period key identifier. Required.
        :type quota_period_key: str
        :param parameters: The value of the Quota counter to be applied on the specified period.
         Required.
        :type parameters: ~azure.mgmt.apimanagement.models.QuotaCounterValueUpdateContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: QuotaCounterContract. The QuotaCounterContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.QuotaCounterContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        quota_counter_key: str,
        quota_period_key: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.QuotaCounterContract:
        """Updates an existing quota counter value in the specified service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param quota_counter_key: Quota counter key identifier. This is the result of expression
         defined in ``counter-key`` attribute of the quota-by-key policy. For example, if you specify
         ``counter-key="boo"`` in the policy, then it’s accessible by ``"boo"`` counter key. But if it’s
         defined as ``counter-key="@("b"+"a")"`` then it will be accessible by ``"ba"`` key. Required.
        :type quota_counter_key: str
        :param quota_period_key: Quota period key identifier. Required.
        :type quota_period_key: str
        :param parameters: The value of the Quota counter to be applied on the specified period.
         Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: QuotaCounterContract. The QuotaCounterContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.QuotaCounterContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        quota_counter_key: str,
        quota_period_key: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.QuotaCounterContract:
        """Updates an existing quota counter value in the specified service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param quota_counter_key: Quota counter key identifier. This is the result of expression
         defined in ``counter-key`` attribute of the quota-by-key policy. For example, if you specify
         ``counter-key="boo"`` in the policy, then it’s accessible by ``"boo"`` counter key. But if it’s
         defined as ``counter-key="@("b"+"a")"`` then it will be accessible by ``"ba"`` key. Required.
        :type quota_counter_key: str
        :param quota_period_key: Quota period key identifier. Required.
        :type quota_period_key: str
        :param parameters: The value of the Quota counter to be applied on the specified period.
         Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: QuotaCounterContract. The QuotaCounterContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.QuotaCounterContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        quota_counter_key: str,
        quota_period_key: str,
        parameters: Union[_models.QuotaCounterValueUpdateContract, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.QuotaCounterContract:
        """Updates an existing quota counter value in the specified service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param quota_counter_key: Quota counter key identifier. This is the result of expression
         defined in ``counter-key`` attribute of the quota-by-key policy. For example, if you specify
         ``counter-key="boo"`` in the policy, then it’s accessible by ``"boo"`` counter key. But if it’s
         defined as ``counter-key="@("b"+"a")"`` then it will be accessible by ``"ba"`` key. Required.
        :type quota_counter_key: str
        :param quota_period_key: Quota period key identifier. Required.
        :type quota_period_key: str
        :param parameters: The value of the Quota counter to be applied on the specified period. Is one
         of the following types: QuotaCounterValueUpdateContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.QuotaCounterValueUpdateContract or JSON or
         IO[bytes]
        :return: QuotaCounterContract. The QuotaCounterContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.QuotaCounterContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.QuotaCounterContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_quota_by_period_keys_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            quota_counter_key=quota_counter_key,
            quota_period_key=quota_period_key,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.QuotaCounterContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class RegionOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`region` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list_by_service(
        self, resource_group_name: str, service_name: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.RegionContract"]:
        """Lists all azure regions in which the service exists.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :return: An iterator like instance of RegionContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.RegionContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.RegionContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_region_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.RegionContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class ReportsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`reports` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list_by_api(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        filter: str,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        orderby: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.ReportRecordContract"]:
        """Lists report records by API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: The filter to apply on the operation. Required.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :keyword orderby: OData order by query option. Default value is None.
        :paramtype orderby: str
        :return: An iterator like instance of ReportRecordContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ReportRecordContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ReportRecordContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_reports_list_by_api_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    orderby=orderby,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ReportRecordContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list_by_user(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        filter: str,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        orderby: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.ReportRecordContract"]:
        """Lists report records by User.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: |   Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| timestamp |
         filter | ge, le |     | </br>| displayName | select, orderBy |     |     | </br>| userId |
         select, filter | eq |     | </br>| apiRegion | filter | eq |     | </br>| productId | filter |
         eq |     | </br>| subscriptionId | filter | eq |     | </br>| apiId | filter | eq |     |
         </br>| operationId | filter | eq |     | </br>| callCountSuccess | select, orderBy |     |
         | </br>| callCountBlocked | select, orderBy |     |     | </br>| callCountFailed | select,
         orderBy |     |     | </br>| callCountOther | select, orderBy |     |     | </br>|
         callCountTotal | select, orderBy |     |     | </br>| bandwidth | select, orderBy |     |     |
         </br>| cacheHitsCount | select |     |     | </br>| cacheMissCount | select |     |     |
         </br>| apiTimeAvg | select, orderBy |     |     | </br>| apiTimeMin | select |     |     |
         </br>| apiTimeMax | select |     |     | </br>| serviceTimeAvg | select |     |     | </br>|
         serviceTimeMin | select |     |     | </br>| serviceTimeMax | select |     |     | </br>.
         Required.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :keyword orderby: OData order by query option. Default value is None.
        :paramtype orderby: str
        :return: An iterator like instance of ReportRecordContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ReportRecordContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ReportRecordContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_reports_list_by_user_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    orderby=orderby,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ReportRecordContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list_by_operation(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        filter: str,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        orderby: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.ReportRecordContract"]:
        """Lists report records by API Operations.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: |   Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| timestamp |
         filter | ge, le |     | </br>| displayName | select, orderBy |     |     | </br>| apiRegion |
         filter | eq |     | </br>| userId | filter | eq |     | </br>| productId | filter | eq |     |
         </br>| subscriptionId | filter | eq |     | </br>| apiId | filter | eq |     | </br>|
         operationId | select, filter | eq |     | </br>| callCountSuccess | select, orderBy |     |
         | </br>| callCountBlocked | select, orderBy |     |     | </br>| callCountFailed | select,
         orderBy |     |     | </br>| callCountOther | select, orderBy |     |     | </br>|
         callCountTotal | select, orderBy |     |     | </br>| bandwidth | select, orderBy |     |     |
         </br>| cacheHitsCount | select |     |     | </br>| cacheMissCount | select |     |     |
         </br>| apiTimeAvg | select, orderBy |     |     | </br>| apiTimeMin | select |     |     |
         </br>| apiTimeMax | select |     |     | </br>| serviceTimeAvg | select |     |     | </br>|
         serviceTimeMin | select |     |     | </br>| serviceTimeMax | select |     |     | </br>.
         Required.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :keyword orderby: OData order by query option. Default value is None.
        :paramtype orderby: str
        :return: An iterator like instance of ReportRecordContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ReportRecordContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ReportRecordContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_reports_list_by_operation_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    orderby=orderby,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ReportRecordContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list_by_product(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        filter: str,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        orderby: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.ReportRecordContract"]:
        """Lists report records by Product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: |   Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| timestamp |
         filter | ge, le |     | </br>| displayName | select, orderBy |     |     | </br>| apiRegion |
         filter | eq |     | </br>| userId | filter | eq |     | </br>| productId | select, filter | eq
         |     | </br>| subscriptionId | filter | eq |     | </br>| callCountSuccess | select, orderBy |
         |     | </br>| callCountBlocked | select, orderBy |     |     | </br>| callCountFailed |
         select, orderBy |     |     | </br>| callCountOther | select, orderBy |     |     | </br>|
         callCountTotal | select, orderBy |     |     | </br>| bandwidth | select, orderBy |     |     |
         </br>| cacheHitsCount | select |     |     | </br>| cacheMissCount | select |     |     |
         </br>| apiTimeAvg | select, orderBy |     |     | </br>| apiTimeMin | select |     |     |
         </br>| apiTimeMax | select |     |     | </br>| serviceTimeAvg | select |     |     | </br>|
         serviceTimeMin | select |     |     | </br>| serviceTimeMax | select |     |     | </br>.
         Required.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :keyword orderby: OData order by query option. Default value is None.
        :paramtype orderby: str
        :return: An iterator like instance of ReportRecordContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ReportRecordContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ReportRecordContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_reports_list_by_product_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    orderby=orderby,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ReportRecordContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list_by_geo(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        filter: str,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.ReportRecordContract"]:
        """Lists report records by geography.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: |   Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| timestamp |
         filter | ge, le |     | </br>| country | select |     |     | </br>| region | select |     |
         | </br>| zip | select |     |     | </br>| apiRegion | filter | eq |     | </br>| userId |
         filter | eq |     | </br>| productId | filter | eq |     | </br>| subscriptionId | filter | eq
         |     | </br>| apiId | filter | eq |     | </br>| operationId | filter | eq |     | </br>|
         callCountSuccess | select |     |     | </br>| callCountBlocked | select |     |     | </br>|
         callCountFailed | select |     |     | </br>| callCountOther | select |     |     | </br>|
         bandwidth | select, orderBy |     |     | </br>| cacheHitsCount | select |     |     | </br>|
         cacheMissCount | select |     |     | </br>| apiTimeAvg | select |     |     | </br>|
         apiTimeMin | select |     |     | </br>| apiTimeMax | select |     |     | </br>|
         serviceTimeAvg | select |     |     | </br>| serviceTimeMin | select |     |     | </br>|
         serviceTimeMax | select |     |     | </br>. Required.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of ReportRecordContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ReportRecordContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ReportRecordContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_reports_list_by_geo_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ReportRecordContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list_by_subscription(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        filter: str,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        orderby: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.ReportRecordContract"]:
        """Lists report records by subscription.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: |   Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| timestamp |
         filter | ge, le |     | </br>| displayName | select, orderBy |     |     | </br>| apiRegion |
         filter | eq |     | </br>| userId | select, filter | eq |     | </br>| productId | select,
         filter | eq |     | </br>| subscriptionId | select, filter | eq |     | </br>| callCountSuccess
         | select, orderBy |     |     | </br>| callCountBlocked | select, orderBy |     |     | </br>|
         callCountFailed | select, orderBy |     |     | </br>| callCountOther | select, orderBy |     |
         | </br>| callCountTotal | select, orderBy |     |     | </br>| bandwidth | select, orderBy |
         |     | </br>| cacheHitsCount | select |     |     | </br>| cacheMissCount | select |     |
         | </br>| apiTimeAvg | select, orderBy |     |     | </br>| apiTimeMin | select |     |     |
         </br>| apiTimeMax | select |     |     | </br>| serviceTimeAvg | select |     |     | </br>|
         serviceTimeMin | select |     |     | </br>| serviceTimeMax | select |     |     | </br>.
         Required.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :keyword orderby: OData order by query option. Default value is None.
        :paramtype orderby: str
        :return: An iterator like instance of ReportRecordContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ReportRecordContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ReportRecordContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_reports_list_by_subscription_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    orderby=orderby,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ReportRecordContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list_by_time(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        filter: str,
        interval: datetime.timedelta,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        orderby: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.ReportRecordContract"]:
        """Lists report records by Time.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: |   Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| timestamp |
         filter, select | ge, le |     | </br>| interval | select |     |     | </br>| apiRegion |
         filter | eq |     | </br>| userId | filter | eq |     | </br>| productId | filter | eq |     |
         </br>| subscriptionId | filter | eq |     | </br>| apiId | filter | eq |     | </br>|
         operationId | filter | eq |     | </br>| callCountSuccess | select |     |     | </br>|
         callCountBlocked | select |     |     | </br>| callCountFailed | select |     |     | </br>|
         callCountOther | select |     |     | </br>| bandwidth | select, orderBy |     |     | </br>|
         cacheHitsCount | select |     |     | </br>| cacheMissCount | select |     |     | </br>|
         apiTimeAvg | select |     |     | </br>| apiTimeMin | select |     |     | </br>| apiTimeMax |
         select |     |     | </br>| serviceTimeAvg | select |     |     | </br>| serviceTimeMin |
         select |     |     | </br>| serviceTimeMax | select |     |     | </br>. Required.
        :paramtype filter: str
        :keyword interval: By time interval. Interval must be multiple of 15 minutes and may not be
         zero. The value should be in ISO  8601 format
         (`http://en.wikipedia.org/wiki/ISO_8601#Durations).This
         <http://en.wikipedia.org/wiki/ISO_8601#Durations).This>`_ code can be used to convert TimeSpan
         to a valid interval string: XmlConvert.ToString(new TimeSpan(hours, minutes, seconds)).
         Required.
        :paramtype interval: ~datetime.timedelta
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :keyword orderby: OData order by query option. Default value is None.
        :paramtype orderby: str
        :return: An iterator like instance of ReportRecordContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ReportRecordContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ReportRecordContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_reports_list_by_time_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    interval=interval,
                    top=top,
                    skip=skip,
                    orderby=orderby,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ReportRecordContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list_by_request(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        filter: str,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.RequestReportRecordContract"]:
        """Lists report records by Request.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: |   Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| timestamp |
         filter | ge, le |     | </br>| apiId | filter | eq |     | </br>| operationId | filter | eq |
         | </br>| productId | filter | eq |     | </br>| userId | filter | eq |     | </br>| apiRegion |
         filter | eq |     | </br>| subscriptionId | filter | eq |     | </br>. Required.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of RequestReportRecordContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.RequestReportRecordContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.RequestReportRecordContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_reports_list_by_request_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.RequestReportRecordContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class TagResourceOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`tag_resource` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.TagResourceContract"]:
        """Lists a collection of resources associated with tags.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| aid |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         displayName | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>| apiName | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>| apiRevision | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
         endswith |</br>| path | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
         endswith |</br>| description | filter | ge, le, eq, ne, gt, lt | substringof, contains,
         startswith, endswith |</br>| serviceUrl | filter | ge, le, eq, ne, gt, lt | substringof,
         contains, startswith, endswith |</br>| method | filter | ge, le, eq, ne, gt, lt | substringof,
         contains, startswith, endswith |</br>| urlTemplate | filter | ge, le, eq, ne, gt, lt |
         substringof, contains, startswith, endswith |</br>| terms | filter | ge, le, eq, ne, gt, lt |
         substringof, contains, startswith, endswith |</br>| state | filter | eq |     |</br>| isCurrent
         | filter | eq |     |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of TagResourceContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.TagResourceContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.TagResourceContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_tag_resource_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.TagResourceContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class ApiReleaseOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`api_release` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, api_id: str, release_id: str, **kwargs: Any
    ) -> _models.ApiReleaseContract:
        """Returns the details of an API release.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param release_id: Release identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type release_id: str
        :return: ApiReleaseContract. The ApiReleaseContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiReleaseContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ApiReleaseContract] = kwargs.pop("cls", None)

        _request = build_api_release_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            release_id=release_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ApiReleaseContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, api_id: str, release_id: str, **kwargs: Any
    ) -> bool:
        """Returns the etag of an API release.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param release_id: Release identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type release_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_api_release_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            release_id=release_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        release_id: str,
        parameters: _models.ApiReleaseContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ApiReleaseContract:
        """Creates a new Release for the API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param release_id: Release identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type release_id: str
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiReleaseContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ApiReleaseContract. The ApiReleaseContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiReleaseContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        release_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ApiReleaseContract:
        """Creates a new Release for the API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param release_id: Release identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type release_id: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ApiReleaseContract. The ApiReleaseContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiReleaseContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        release_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ApiReleaseContract:
        """Creates a new Release for the API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param release_id: Release identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type release_id: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ApiReleaseContract. The ApiReleaseContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiReleaseContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        release_id: str,
        parameters: Union[_models.ApiReleaseContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ApiReleaseContract:
        """Creates a new Release for the API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param release_id: Release identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type release_id: str
        :param parameters: Create parameters. Is one of the following types: ApiReleaseContract, JSON,
         IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiReleaseContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ApiReleaseContract. The ApiReleaseContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiReleaseContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ApiReleaseContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_api_release_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            release_id=release_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ApiReleaseContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        release_id: str,
        parameters: _models.ApiReleaseContract,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ApiReleaseContract:
        """Updates the details of the release of the API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param release_id: Release identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type release_id: str
        :param parameters: API Release Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiReleaseContract
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ApiReleaseContract. The ApiReleaseContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiReleaseContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        release_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ApiReleaseContract:
        """Updates the details of the release of the API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param release_id: Release identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type release_id: str
        :param parameters: API Release Update parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ApiReleaseContract. The ApiReleaseContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiReleaseContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        release_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ApiReleaseContract:
        """Updates the details of the release of the API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param release_id: Release identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type release_id: str
        :param parameters: API Release Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ApiReleaseContract. The ApiReleaseContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiReleaseContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        release_id: str,
        parameters: Union[_models.ApiReleaseContract, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.ApiReleaseContract:
        """Updates the details of the release of the API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param release_id: Release identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type release_id: str
        :param parameters: API Release Update parameters. Is one of the following types:
         ApiReleaseContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiReleaseContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ApiReleaseContract. The ApiReleaseContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiReleaseContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ApiReleaseContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_api_release_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            release_id=release_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ApiReleaseContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        release_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes the specified release in the API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param release_id: Release identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type release_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_api_release_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            release_id=release_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.ApiReleaseContract"]:
        """Lists all releases of an API. An API release is created when making an API Revision current.
        Releases are also used to rollback to previous revisions. Results will be paged and can be
        constrained by the $top and $skip parameters.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| notes |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of ApiReleaseContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ApiReleaseContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ApiReleaseContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_api_release_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    api_id=api_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ApiReleaseContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class ApiOperationOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`api_operation` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, api_id: str, operation_id: str, **kwargs: Any
    ) -> _models.OperationContract:
        """Gets the details of the API Operation specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :return: OperationContract. The OperationContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.OperationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.OperationContract] = kwargs.pop("cls", None)

        _request = build_api_operation_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            operation_id=operation_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.OperationContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, api_id: str, operation_id: str, **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the API operation specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_api_operation_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            operation_id=operation_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        operation_id: str,
        parameters: _models.OperationContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.OperationContract:
        """Creates a new operation in the API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.OperationContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: OperationContract. The OperationContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.OperationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        operation_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.OperationContract:
        """Creates a new operation in the API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: OperationContract. The OperationContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.OperationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        operation_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.OperationContract:
        """Creates a new operation in the API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: OperationContract. The OperationContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.OperationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        operation_id: str,
        parameters: Union[_models.OperationContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.OperationContract:
        """Creates a new operation in the API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :param parameters: Create parameters. Is one of the following types: OperationContract, JSON,
         IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.OperationContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: OperationContract. The OperationContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.OperationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.OperationContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_api_operation_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            operation_id=operation_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.OperationContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        operation_id: str,
        parameters: _models.OperationUpdateContract,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.OperationContract:
        """Updates the details of the operation in the API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :param parameters: API Operation Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.OperationUpdateContract
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: OperationContract. The OperationContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.OperationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        operation_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.OperationContract:
        """Updates the details of the operation in the API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :param parameters: API Operation Update parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: OperationContract. The OperationContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.OperationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        operation_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.OperationContract:
        """Updates the details of the operation in the API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :param parameters: API Operation Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: OperationContract. The OperationContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.OperationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        operation_id: str,
        parameters: Union[_models.OperationUpdateContract, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.OperationContract:
        """Updates the details of the operation in the API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :param parameters: API Operation Update parameters. Is one of the following types:
         OperationUpdateContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.OperationUpdateContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: OperationContract. The OperationContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.OperationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.OperationContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_api_operation_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            operation_id=operation_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.OperationContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        operation_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes the specified operation in the API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_api_operation_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            operation_id=operation_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_api(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        tags: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.OperationContract"]:
        """Lists a collection of the operations for the specified API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         displayName | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>| method | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>| description | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
         endswith |</br>| urlTemplate | filter | ge, le, eq, ne, gt, lt | substringof, contains,
         startswith, endswith |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :keyword tags: Include tags in the response. Default value is None.
        :paramtype tags: str
        :return: An iterator like instance of OperationContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.OperationContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.OperationContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_api_operation_list_by_api_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    api_id=api_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    tags=tags,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.OperationContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class ApiOperationPolicyOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`api_operation_policy` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        operation_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        *,
        format: Optional[Union[str, _models.PolicyExportFormat]] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Get the policy configuration at the API Operation level.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :keyword format: Policy Export Format. Known values are: "xml" and "rawxml". Default value is
         None.
        :paramtype format: str or ~azure.mgmt.apimanagement.models.PolicyExportFormat
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.PolicyContract] = kwargs.pop("cls", None)

        _request = build_api_operation_policy_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            operation_id=operation_id,
            policy_id=policy_id,
            subscription_id=self._config.subscription_id,
            format=format,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PolicyContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        operation_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the API operation policy specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_api_operation_policy_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            operation_id=operation_id,
            policy_id=policy_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        operation_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        parameters: _models.PolicyContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Creates or updates policy configuration for the API Operation level.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :param parameters: The policy contents to apply. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PolicyContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        operation_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Creates or updates policy configuration for the API Operation level.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :param parameters: The policy contents to apply. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        operation_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Creates or updates policy configuration for the API Operation level.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :param parameters: The policy contents to apply. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        operation_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        parameters: Union[_models.PolicyContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyContract:
        """Creates or updates policy configuration for the API Operation level.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :param parameters: The policy contents to apply. Is one of the following types: PolicyContract,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PolicyContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyContract. The PolicyContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.PolicyContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_api_operation_policy_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            operation_id=operation_id,
            policy_id=policy_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PolicyContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        operation_id: str,
        policy_id: Union[str, _models.PolicyIdName],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes the policy configuration at the Api Operation.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :param policy_id: The identifier of the Policy. "policy" Required.
        :type policy_id: str or ~azure.mgmt.apimanagement.models.PolicyIdName
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_api_operation_policy_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            operation_id=operation_id,
            policy_id=policy_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace_async
    async def list_by_operation(
        self, resource_group_name: str, service_name: str, api_id: str, operation_id: str, **kwargs: Any
    ) -> _models.PolicyCollection:
        """Get the list of policy configuration at the API Operation level.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param operation_id: Operation identifier within an API. Must be unique in the current API
         Management service instance. Required.
        :type operation_id: str
        :return: PolicyCollection. The PolicyCollection is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyCollection
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.PolicyCollection] = kwargs.pop("cls", None)

        _request = build_api_operation_policy_list_by_operation_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            operation_id=operation_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PolicyCollection, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class GraphQLApiResolverOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`graph_ql_api_resolver` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, api_id: str, resolver_id: str, **kwargs: Any
    ) -> _models.ResolverContract:
        """Gets the details of the GraphQL API Resolver specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param resolver_id: Resolver identifier within a GraphQL API. Must be unique in the current API
         Management service instance. Required.
        :type resolver_id: str
        :return: ResolverContract. The ResolverContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ResolverContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ResolverContract] = kwargs.pop("cls", None)

        _request = build_graph_ql_api_resolver_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            resolver_id=resolver_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ResolverContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, api_id: str, resolver_id: str, **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the GraphQL API resolver specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param resolver_id: Resolver identifier within a GraphQL API. Must be unique in the current API
         Management service instance. Required.
        :type resolver_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_graph_ql_api_resolver_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            resolver_id=resolver_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        resolver_id: str,
        parameters: _models.ResolverContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ResolverContract:
        """Creates a new resolver in the GraphQL API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param resolver_id: Resolver identifier within a GraphQL API. Must be unique in the current API
         Management service instance. Required.
        :type resolver_id: str
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ResolverContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ResolverContract. The ResolverContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ResolverContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        resolver_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ResolverContract:
        """Creates a new resolver in the GraphQL API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param resolver_id: Resolver identifier within a GraphQL API. Must be unique in the current API
         Management service instance. Required.
        :type resolver_id: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ResolverContract. The ResolverContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ResolverContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        resolver_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ResolverContract:
        """Creates a new resolver in the GraphQL API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param resolver_id: Resolver identifier within a GraphQL API. Must be unique in the current API
         Management service instance. Required.
        :type resolver_id: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ResolverContract. The ResolverContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ResolverContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        resolver_id: str,
        parameters: Union[_models.ResolverContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ResolverContract:
        """Creates a new resolver in the GraphQL API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param resolver_id: Resolver identifier within a GraphQL API. Must be unique in the current API
         Management service instance. Required.
        :type resolver_id: str
        :param parameters: Create parameters. Is one of the following types: ResolverContract, JSON,
         IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ResolverContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ResolverContract. The ResolverContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ResolverContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ResolverContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_graph_ql_api_resolver_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            resolver_id=resolver_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ResolverContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        resolver_id: str,
        parameters: _models.ResolverUpdateContract,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ResolverContract:
        """Updates the details of the resolver in the GraphQL API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param resolver_id: Resolver identifier within a GraphQL API. Must be unique in the current API
         Management service instance. Required.
        :type resolver_id: str
        :param parameters: GraphQL API Resolver Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ResolverUpdateContract
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ResolverContract. The ResolverContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ResolverContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        resolver_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ResolverContract:
        """Updates the details of the resolver in the GraphQL API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param resolver_id: Resolver identifier within a GraphQL API. Must be unique in the current API
         Management service instance. Required.
        :type resolver_id: str
        :param parameters: GraphQL API Resolver Update parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ResolverContract. The ResolverContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ResolverContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        resolver_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ResolverContract:
        """Updates the details of the resolver in the GraphQL API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param resolver_id: Resolver identifier within a GraphQL API. Must be unique in the current API
         Management service instance. Required.
        :type resolver_id: str
        :param parameters: GraphQL API Resolver Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ResolverContract. The ResolverContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ResolverContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        resolver_id: str,
        parameters: Union[_models.ResolverUpdateContract, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.ResolverContract:
        """Updates the details of the resolver in the GraphQL API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param resolver_id: Resolver identifier within a GraphQL API. Must be unique in the current API
         Management service instance. Required.
        :type resolver_id: str
        :param parameters: GraphQL API Resolver Update parameters. Is one of the following types:
         ResolverUpdateContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ResolverUpdateContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ResolverContract. The ResolverContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ResolverContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ResolverContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_graph_ql_api_resolver_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            resolver_id=resolver_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ResolverContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        resolver_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes the specified resolver in the GraphQL API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param resolver_id: Resolver identifier within a GraphQL API. Must be unique in the current API
         Management service instance. Required.
        :type resolver_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_graph_ql_api_resolver_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            resolver_id=resolver_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_api(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.ResolverContract"]:
        """Lists a collection of the resolvers for the specified GraphQL API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         displayName | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>| description | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
         endswith |</br>| path | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
         endswith |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of ResolverContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ResolverContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ResolverContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_graph_ql_api_resolver_list_by_api_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    api_id=api_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ResolverContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class ApiSchemaOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`api_schema` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, api_id: str, schema_id: str, **kwargs: Any
    ) -> _models.SchemaContract:
        """Get the schema configuration at the API level.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param schema_id: Schema id identifier. Must be unique in the current API Management service
         instance. Required.
        :type schema_id: str
        :return: SchemaContract. The SchemaContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.SchemaContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.SchemaContract] = kwargs.pop("cls", None)

        _request = build_api_schema_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            schema_id=schema_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.SchemaContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, api_id: str, schema_id: str, **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the schema specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param schema_id: Schema id identifier. Must be unique in the current API Management service
         instance. Required.
        :type schema_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_api_schema_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            schema_id=schema_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    async def _create_or_update_initial(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        schema_id: str,
        parameters: Union[_models.SchemaContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_api_schema_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            schema_id=schema_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 200:
            response_headers["Azure-AsyncOperation"] = self._deserialize(
                "str", response.headers.get("Azure-AsyncOperation")
            )
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if response.status_code == 201:
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))
            response_headers["Azure-AsyncOperation"] = self._deserialize(
                "str", response.headers.get("Azure-AsyncOperation")
            )
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        schema_id: str,
        parameters: _models.SchemaContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.SchemaContract]:
        """Creates or updates schema configuration for the API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param schema_id: Schema id identifier. Must be unique in the current API Management service
         instance. Required.
        :type schema_id: str
        :param parameters: The schema contents to apply. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.SchemaContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns SchemaContract. The SchemaContract is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.SchemaContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        schema_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.SchemaContract]:
        """Creates or updates schema configuration for the API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param schema_id: Schema id identifier. Must be unique in the current API Management service
         instance. Required.
        :type schema_id: str
        :param parameters: The schema contents to apply. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns SchemaContract. The SchemaContract is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.SchemaContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        schema_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.SchemaContract]:
        """Creates or updates schema configuration for the API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param schema_id: Schema id identifier. Must be unique in the current API Management service
         instance. Required.
        :type schema_id: str
        :param parameters: The schema contents to apply. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns SchemaContract. The SchemaContract is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.SchemaContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        schema_id: str,
        parameters: Union[_models.SchemaContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.SchemaContract]:
        """Creates or updates schema configuration for the API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param schema_id: Schema id identifier. Must be unique in the current API Management service
         instance. Required.
        :type schema_id: str
        :param parameters: The schema contents to apply. Is one of the following types: SchemaContract,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.SchemaContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns SchemaContract. The SchemaContract is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.SchemaContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.SchemaContract] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._create_or_update_initial(
                resource_group_name=resource_group_name,
                service_name=service_name,
                api_id=api_id,
                schema_id=schema_id,
                parameters=parameters,
                etag=etag,
                match_condition=match_condition,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response_headers = {}
            response = pipeline_response.http_response
            response_headers["Azure-AsyncOperation"] = self._deserialize(
                "str", response.headers.get("Azure-AsyncOperation")
            )
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

            deserialized = _deserialize(_models.SchemaContract, response.json())
            if cls:
                return cls(pipeline_response, deserialized, response_headers)  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.SchemaContract].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.SchemaContract](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        schema_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        force: Optional[bool] = None,
        **kwargs: Any
    ) -> None:
        """Deletes the schema configuration at the Api.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param schema_id: Schema id identifier. Must be unique in the current API Management service
         instance. Required.
        :type schema_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword force: If true removes all references to the schema before deleting it. Default value
         is None.
        :paramtype force: bool
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_api_schema_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            schema_id=schema_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            force=force,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_api(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.SchemaContract"]:
        """Get the schema configuration at the API level.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| contentType
         | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of SchemaContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.SchemaContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.SchemaContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_api_schema_list_by_api_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    api_id=api_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.SchemaContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class ApiDiagnosticOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`api_diagnostic` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, api_id: str, diagnostic_id: str, **kwargs: Any
    ) -> _models.DiagnosticContract:
        """Gets the details of the Diagnostic for an API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :return: DiagnosticContract. The DiagnosticContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.DiagnosticContract] = kwargs.pop("cls", None)

        _request = build_api_diagnostic_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            diagnostic_id=diagnostic_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.DiagnosticContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, api_id: str, diagnostic_id: str, **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the Diagnostic for an API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_api_diagnostic_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            diagnostic_id=diagnostic_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        diagnostic_id: str,
        parameters: _models.DiagnosticContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.DiagnosticContract:
        """Creates a new Diagnostic for an API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: DiagnosticContract. The DiagnosticContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        diagnostic_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.DiagnosticContract:
        """Creates a new Diagnostic for an API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: DiagnosticContract. The DiagnosticContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        diagnostic_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.DiagnosticContract:
        """Creates a new Diagnostic for an API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: DiagnosticContract. The DiagnosticContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        diagnostic_id: str,
        parameters: Union[_models.DiagnosticContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.DiagnosticContract:
        """Creates a new Diagnostic for an API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :param parameters: Create parameters. Is one of the following types: DiagnosticContract, JSON,
         IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.DiagnosticContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: DiagnosticContract. The DiagnosticContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.DiagnosticContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_api_diagnostic_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            diagnostic_id=diagnostic_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.DiagnosticContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        diagnostic_id: str,
        parameters: _models.DiagnosticContract,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.DiagnosticContract:
        """Updates the details of the Diagnostic for an API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :param parameters: Diagnostic Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: DiagnosticContract. The DiagnosticContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        diagnostic_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.DiagnosticContract:
        """Updates the details of the Diagnostic for an API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :param parameters: Diagnostic Update parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: DiagnosticContract. The DiagnosticContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        diagnostic_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.DiagnosticContract:
        """Updates the details of the Diagnostic for an API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :param parameters: Diagnostic Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: DiagnosticContract. The DiagnosticContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        diagnostic_id: str,
        parameters: Union[_models.DiagnosticContract, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.DiagnosticContract:
        """Updates the details of the Diagnostic for an API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :param parameters: Diagnostic Update parameters. Is one of the following types:
         DiagnosticContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.DiagnosticContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: DiagnosticContract. The DiagnosticContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.DiagnosticContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_api_diagnostic_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            diagnostic_id=diagnostic_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.DiagnosticContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        diagnostic_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes the specified Diagnostic from an API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
         service instance. Required.
        :type diagnostic_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_api_diagnostic_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            diagnostic_id=diagnostic_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.DiagnosticContract"]:
        """Lists all diagnostics of an API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of DiagnosticContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.DiagnosticContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.DiagnosticContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_api_diagnostic_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    api_id=api_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.DiagnosticContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class ApiIssueOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`api_issue` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        issue_id: str,
        *,
        expand_comments_attachments: Optional[bool] = None,
        **kwargs: Any
    ) -> _models.IssueContract:
        """Gets the details of the Issue for an API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param issue_id: Issue identifier. Must be unique in the current API Management service
         instance. Required.
        :type issue_id: str
        :keyword expand_comments_attachments: Expand the comment attachments. Default value is None.
        :paramtype expand_comments_attachments: bool
        :return: IssueContract. The IssueContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.IssueContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.IssueContract] = kwargs.pop("cls", None)

        _request = build_api_issue_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            issue_id=issue_id,
            subscription_id=self._config.subscription_id,
            expand_comments_attachments=expand_comments_attachments,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.IssueContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, api_id: str, issue_id: str, **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the Issue for an API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param issue_id: Issue identifier. Must be unique in the current API Management service
         instance. Required.
        :type issue_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_api_issue_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            issue_id=issue_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        issue_id: str,
        parameters: _models.IssueContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.IssueContract:
        """Creates a new Issue for an API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param issue_id: Issue identifier. Must be unique in the current API Management service
         instance. Required.
        :type issue_id: str
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.IssueContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: IssueContract. The IssueContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.IssueContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        issue_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.IssueContract:
        """Creates a new Issue for an API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param issue_id: Issue identifier. Must be unique in the current API Management service
         instance. Required.
        :type issue_id: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: IssueContract. The IssueContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.IssueContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        issue_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.IssueContract:
        """Creates a new Issue for an API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param issue_id: Issue identifier. Must be unique in the current API Management service
         instance. Required.
        :type issue_id: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: IssueContract. The IssueContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.IssueContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        issue_id: str,
        parameters: Union[_models.IssueContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.IssueContract:
        """Creates a new Issue for an API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param issue_id: Issue identifier. Must be unique in the current API Management service
         instance. Required.
        :type issue_id: str
        :param parameters: Create parameters. Is one of the following types: IssueContract, JSON,
         IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.IssueContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: IssueContract. The IssueContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.IssueContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.IssueContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_api_issue_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            issue_id=issue_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 200:
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if response.status_code == 201:
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.IssueContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        issue_id: str,
        parameters: _models.IssueUpdateContract,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.IssueContract:
        """Updates an existing issue for an API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param issue_id: Issue identifier. Must be unique in the current API Management service
         instance. Required.
        :type issue_id: str
        :param parameters: Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.IssueUpdateContract
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: IssueContract. The IssueContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.IssueContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        issue_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.IssueContract:
        """Updates an existing issue for an API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param issue_id: Issue identifier. Must be unique in the current API Management service
         instance. Required.
        :type issue_id: str
        :param parameters: Update parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: IssueContract. The IssueContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.IssueContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        issue_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.IssueContract:
        """Updates an existing issue for an API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param issue_id: Issue identifier. Must be unique in the current API Management service
         instance. Required.
        :type issue_id: str
        :param parameters: Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: IssueContract. The IssueContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.IssueContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        issue_id: str,
        parameters: Union[_models.IssueUpdateContract, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.IssueContract:
        """Updates an existing issue for an API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param issue_id: Issue identifier. Must be unique in the current API Management service
         instance. Required.
        :type issue_id: str
        :param parameters: Update parameters. Is one of the following types: IssueUpdateContract, JSON,
         IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.IssueUpdateContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: IssueContract. The IssueContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.IssueContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.IssueContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_api_issue_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            issue_id=issue_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.IssueContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        issue_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes the specified Issue from an API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param issue_id: Issue identifier. Must be unique in the current API Management service
         instance. Required.
        :type issue_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_api_issue_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            issue_id=issue_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        *,
        filter: Optional[str] = None,
        expand_comments_attachments: Optional[bool] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.IssueContract"]:
        """Lists all issues associated with the specified API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>| userId |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>| state |
         filter | eq |     |</br>. Default value is None.
        :paramtype filter: str
        :keyword expand_comments_attachments: Expand the comment attachments. Default value is None.
        :paramtype expand_comments_attachments: bool
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of IssueContract
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.IssueContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.IssueContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_api_issue_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    api_id=api_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    expand_comments_attachments=expand_comments_attachments,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.IssueContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class ApiIssueCommentOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`api_issue_comment` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, api_id: str, issue_id: str, comment_id: str, **kwargs: Any
    ) -> _models.IssueCommentContract:
        """Gets the details of the issue Comment for an API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param issue_id: Issue identifier. Must be unique in the current API Management service
         instance. Required.
        :type issue_id: str
        :param comment_id: Comment identifier within an Issue. Must be unique in the current Issue.
         Required.
        :type comment_id: str
        :return: IssueCommentContract. The IssueCommentContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.IssueCommentContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.IssueCommentContract] = kwargs.pop("cls", None)

        _request = build_api_issue_comment_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            issue_id=issue_id,
            comment_id=comment_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.IssueCommentContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, api_id: str, issue_id: str, comment_id: str, **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the issue Comment for an API specified by its
        identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param issue_id: Issue identifier. Must be unique in the current API Management service
         instance. Required.
        :type issue_id: str
        :param comment_id: Comment identifier within an Issue. Must be unique in the current Issue.
         Required.
        :type comment_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_api_issue_comment_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            issue_id=issue_id,
            comment_id=comment_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        issue_id: str,
        comment_id: str,
        parameters: _models.IssueCommentContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.IssueCommentContract:
        """Creates a new Comment for the Issue in an API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param issue_id: Issue identifier. Must be unique in the current API Management service
         instance. Required.
        :type issue_id: str
        :param comment_id: Comment identifier within an Issue. Must be unique in the current Issue.
         Required.
        :type comment_id: str
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.IssueCommentContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: IssueCommentContract. The IssueCommentContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.IssueCommentContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        issue_id: str,
        comment_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.IssueCommentContract:
        """Creates a new Comment for the Issue in an API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param issue_id: Issue identifier. Must be unique in the current API Management service
         instance. Required.
        :type issue_id: str
        :param comment_id: Comment identifier within an Issue. Must be unique in the current Issue.
         Required.
        :type comment_id: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: IssueCommentContract. The IssueCommentContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.IssueCommentContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        issue_id: str,
        comment_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.IssueCommentContract:
        """Creates a new Comment for the Issue in an API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param issue_id: Issue identifier. Must be unique in the current API Management service
         instance. Required.
        :type issue_id: str
        :param comment_id: Comment identifier within an Issue. Must be unique in the current Issue.
         Required.
        :type comment_id: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: IssueCommentContract. The IssueCommentContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.IssueCommentContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        issue_id: str,
        comment_id: str,
        parameters: Union[_models.IssueCommentContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.IssueCommentContract:
        """Creates a new Comment for the Issue in an API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param issue_id: Issue identifier. Must be unique in the current API Management service
         instance. Required.
        :type issue_id: str
        :param comment_id: Comment identifier within an Issue. Must be unique in the current Issue.
         Required.
        :type comment_id: str
        :param parameters: Create parameters. Is one of the following types: IssueCommentContract,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.IssueCommentContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: IssueCommentContract. The IssueCommentContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.IssueCommentContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.IssueCommentContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_api_issue_comment_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            issue_id=issue_id,
            comment_id=comment_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 200:
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if response.status_code == 201:
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.IssueCommentContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        issue_id: str,
        comment_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes the specified comment from an Issue.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param issue_id: Issue identifier. Must be unique in the current API Management service
         instance. Required.
        :type issue_id: str
        :param comment_id: Comment identifier within an Issue. Must be unique in the current Issue.
         Required.
        :type comment_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_api_issue_comment_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            issue_id=issue_id,
            comment_id=comment_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        issue_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.IssueCommentContract"]:
        """Lists all comments for the Issue associated with the specified API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param issue_id: Issue identifier. Must be unique in the current API Management service
         instance. Required.
        :type issue_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>| userId |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of IssueCommentContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.IssueCommentContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.IssueCommentContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_api_issue_comment_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    api_id=api_id,
                    issue_id=issue_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.IssueCommentContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class ApiIssueAttachmentOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`api_issue_attachment` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, api_id: str, issue_id: str, attachment_id: str, **kwargs: Any
    ) -> _models.IssueAttachmentContract:
        """Gets the details of the issue Attachment for an API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param issue_id: Issue identifier. Must be unique in the current API Management service
         instance. Required.
        :type issue_id: str
        :param attachment_id: Attachment identifier within an Issue. Must be unique in the current
         Issue. Required.
        :type attachment_id: str
        :return: IssueAttachmentContract. The IssueAttachmentContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.IssueAttachmentContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.IssueAttachmentContract] = kwargs.pop("cls", None)

        _request = build_api_issue_attachment_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            issue_id=issue_id,
            attachment_id=attachment_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.IssueAttachmentContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, api_id: str, issue_id: str, attachment_id: str, **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the issue Attachment for an API specified by its
        identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param issue_id: Issue identifier. Must be unique in the current API Management service
         instance. Required.
        :type issue_id: str
        :param attachment_id: Attachment identifier within an Issue. Must be unique in the current
         Issue. Required.
        :type attachment_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_api_issue_attachment_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            issue_id=issue_id,
            attachment_id=attachment_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        issue_id: str,
        attachment_id: str,
        parameters: _models.IssueAttachmentContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.IssueAttachmentContract:
        """Creates a new Attachment for the Issue in an API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param issue_id: Issue identifier. Must be unique in the current API Management service
         instance. Required.
        :type issue_id: str
        :param attachment_id: Attachment identifier within an Issue. Must be unique in the current
         Issue. Required.
        :type attachment_id: str
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.IssueAttachmentContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: IssueAttachmentContract. The IssueAttachmentContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.IssueAttachmentContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        issue_id: str,
        attachment_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.IssueAttachmentContract:
        """Creates a new Attachment for the Issue in an API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param issue_id: Issue identifier. Must be unique in the current API Management service
         instance. Required.
        :type issue_id: str
        :param attachment_id: Attachment identifier within an Issue. Must be unique in the current
         Issue. Required.
        :type attachment_id: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: IssueAttachmentContract. The IssueAttachmentContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.IssueAttachmentContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        issue_id: str,
        attachment_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.IssueAttachmentContract:
        """Creates a new Attachment for the Issue in an API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param issue_id: Issue identifier. Must be unique in the current API Management service
         instance. Required.
        :type issue_id: str
        :param attachment_id: Attachment identifier within an Issue. Must be unique in the current
         Issue. Required.
        :type attachment_id: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: IssueAttachmentContract. The IssueAttachmentContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.IssueAttachmentContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        issue_id: str,
        attachment_id: str,
        parameters: Union[_models.IssueAttachmentContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.IssueAttachmentContract:
        """Creates a new Attachment for the Issue in an API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param issue_id: Issue identifier. Must be unique in the current API Management service
         instance. Required.
        :type issue_id: str
        :param attachment_id: Attachment identifier within an Issue. Must be unique in the current
         Issue. Required.
        :type attachment_id: str
        :param parameters: Create parameters. Is one of the following types: IssueAttachmentContract,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.IssueAttachmentContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: IssueAttachmentContract. The IssueAttachmentContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.IssueAttachmentContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.IssueAttachmentContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_api_issue_attachment_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            issue_id=issue_id,
            attachment_id=attachment_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 200:
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if response.status_code == 201:
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.IssueAttachmentContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        issue_id: str,
        attachment_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes the specified comment from an Issue.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param issue_id: Issue identifier. Must be unique in the current API Management service
         instance. Required.
        :type issue_id: str
        :param attachment_id: Attachment identifier within an Issue. Must be unique in the current
         Issue. Required.
        :type attachment_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_api_issue_attachment_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            issue_id=issue_id,
            attachment_id=attachment_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        issue_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.IssueAttachmentContract"]:
        """Lists all attachments for the Issue associated with the specified API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param issue_id: Issue identifier. Must be unique in the current API Management service
         instance. Required.
        :type issue_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>| userId |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of IssueAttachmentContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.IssueAttachmentContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.IssueAttachmentContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_api_issue_attachment_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    api_id=api_id,
                    issue_id=issue_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.IssueAttachmentContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class ApiTagDescriptionOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`api_tag_description` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, api_id: str, tag_description_id: str, **kwargs: Any
    ) -> _models.TagDescriptionContract:
        """Get Tag description in scope of API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param tag_description_id: Tag description identifier. Used when creating tagDescription for
         API/Tag association. Based on API and Tag names. Required.
        :type tag_description_id: str
        :return: TagDescriptionContract. The TagDescriptionContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagDescriptionContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.TagDescriptionContract] = kwargs.pop("cls", None)

        _request = build_api_tag_description_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            tag_description_id=tag_description_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.TagDescriptionContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, api_id: str, tag_description_id: str, **kwargs: Any
    ) -> bool:
        """Gets the entity state version of the tag specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param tag_description_id: Tag description identifier. Used when creating tagDescription for
         API/Tag association. Based on API and Tag names. Required.
        :type tag_description_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_api_tag_description_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            tag_description_id=tag_description_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        tag_description_id: str,
        parameters: _models.TagDescriptionCreateParameters,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.TagDescriptionContract:
        """Create/Update tag description in scope of the Api.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param tag_description_id: Tag description identifier. Used when creating tagDescription for
         API/Tag association. Based on API and Tag names. Required.
        :type tag_description_id: str
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.TagDescriptionCreateParameters
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: TagDescriptionContract. The TagDescriptionContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagDescriptionContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        tag_description_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.TagDescriptionContract:
        """Create/Update tag description in scope of the Api.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param tag_description_id: Tag description identifier. Used when creating tagDescription for
         API/Tag association. Based on API and Tag names. Required.
        :type tag_description_id: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: TagDescriptionContract. The TagDescriptionContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagDescriptionContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        tag_description_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.TagDescriptionContract:
        """Create/Update tag description in scope of the Api.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param tag_description_id: Tag description identifier. Used when creating tagDescription for
         API/Tag association. Based on API and Tag names. Required.
        :type tag_description_id: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: TagDescriptionContract. The TagDescriptionContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagDescriptionContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        tag_description_id: str,
        parameters: Union[_models.TagDescriptionCreateParameters, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.TagDescriptionContract:
        """Create/Update tag description in scope of the Api.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param tag_description_id: Tag description identifier. Used when creating tagDescription for
         API/Tag association. Based on API and Tag names. Required.
        :type tag_description_id: str
        :param parameters: Create parameters. Is one of the following types:
         TagDescriptionCreateParameters, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.TagDescriptionCreateParameters or JSON or
         IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: TagDescriptionContract. The TagDescriptionContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagDescriptionContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.TagDescriptionContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_api_tag_description_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            tag_description_id=tag_description_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 200:
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if response.status_code == 201:
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.TagDescriptionContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        tag_description_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Delete tag description for the Api.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param tag_description_id: Tag description identifier. Used when creating tagDescription for
         API/Tag association. Based on API and Tag names. Required.
        :type tag_description_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_api_tag_description_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            tag_description_id=tag_description_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.TagDescriptionContract"]:
        """Lists all Tags descriptions in scope of API. Model similar to swagger - tagDescription is
        defined on API level but tag may be assigned to the Operations.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| displayName
         | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of TagDescriptionContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.TagDescriptionContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.TagDescriptionContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_api_tag_description_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    api_id=api_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.TagDescriptionContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class ApiWikiOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`api_wiki` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, api_id: str, **kwargs: Any
    ) -> _models.WikiContract:
        """Gets the details of the Wiki for an API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :return: WikiContract. The WikiContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.WikiContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.WikiContract] = kwargs.pop("cls", None)

        _request = build_api_wiki_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.WikiContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(self, resource_group_name: str, service_name: str, api_id: str, **kwargs: Any) -> bool:
        """Gets the entity state (Etag) version of the Wiki for an API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_api_wiki_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        parameters: _models.WikiContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.WikiContract:
        """Creates a new Wiki for an API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.WikiContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: WikiContract. The WikiContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.WikiContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.WikiContract:
        """Creates a new Wiki for an API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: WikiContract. The WikiContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.WikiContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.WikiContract:
        """Creates a new Wiki for an API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: WikiContract. The WikiContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.WikiContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        parameters: Union[_models.WikiContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.WikiContract:
        """Creates a new Wiki for an API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param parameters: Create parameters. Is one of the following types: WikiContract, JSON,
         IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.WikiContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: WikiContract. The WikiContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.WikiContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.WikiContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_api_wiki_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 200:
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if response.status_code == 201:
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.WikiContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        parameters: _models.WikiUpdateContract,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.WikiContract:
        """Updates the details of the Wiki for an API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param parameters: Wiki Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.WikiUpdateContract
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: WikiContract. The WikiContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.WikiContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.WikiContract:
        """Updates the details of the Wiki for an API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param parameters: Wiki Update parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: WikiContract. The WikiContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.WikiContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.WikiContract:
        """Updates the details of the Wiki for an API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param parameters: Wiki Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: WikiContract. The WikiContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.WikiContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        parameters: Union[_models.WikiUpdateContract, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.WikiContract:
        """Updates the details of the Wiki for an API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param parameters: Wiki Update parameters. Is one of the following types: WikiUpdateContract,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.WikiUpdateContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: WikiContract. The WikiContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.WikiContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.WikiContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_api_wiki_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.WikiContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes the specified Wiki from an API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_api_wiki_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore


class ApiWikisOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`api_wikis` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.WikiContract"]:
        """Gets the wikis for an API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | eq |  contains |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of WikiContract
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.WikiContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.WikiContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_api_wikis_list_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    api_id=api_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.WikiContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class ProductWikisOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`product_wikis` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.WikiContract"]:
        """Gets the details of the Wiki for a Product specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | eq |  contains |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of WikiContract
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.WikiContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.WikiContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_product_wikis_list_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    product_id=product_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.WikiContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class ApiToolOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`api_tool` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, api_id: str, tool_id: str, **kwargs: Any
    ) -> _models.ToolContract:
        """Gets the details of the API Tool specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param tool_id: Tool identifier within an API. Must be unique in the current API Management
         service instance. Required.
        :type tool_id: str
        :return: ToolContract. The ToolContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ToolContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ToolContract] = kwargs.pop("cls", None)

        _request = build_api_tool_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            tool_id=tool_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ToolContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, api_id: str, tool_id: str, **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the API tool specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param tool_id: Tool identifier within an API. Must be unique in the current API Management
         service instance. Required.
        :type tool_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_api_tool_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            tool_id=tool_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        tool_id: str,
        parameters: _models.ToolContract,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ToolContract:
        """Creates a new tool in the API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param tool_id: Tool identifier within an API. Must be unique in the current API Management
         service instance. Required.
        :type tool_id: str
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ToolContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ToolContract. The ToolContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ToolContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        tool_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ToolContract:
        """Creates a new tool in the API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param tool_id: Tool identifier within an API. Must be unique in the current API Management
         service instance. Required.
        :type tool_id: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ToolContract. The ToolContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ToolContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        tool_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ToolContract:
        """Creates a new tool in the API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param tool_id: Tool identifier within an API. Must be unique in the current API Management
         service instance. Required.
        :type tool_id: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ToolContract. The ToolContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ToolContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        tool_id: str,
        parameters: Union[_models.ToolContract, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.ToolContract:
        """Creates a new tool in the API or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param tool_id: Tool identifier within an API. Must be unique in the current API Management
         service instance. Required.
        :type tool_id: str
        :param parameters: Create parameters. Is one of the following types: ToolContract, JSON,
         IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ToolContract or JSON or IO[bytes]
        :return: ToolContract. The ToolContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ToolContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ToolContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_api_tool_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            tool_id=tool_id,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 200:
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if response.status_code == 201:
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ToolContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        tool_id: str,
        parameters: _models.ToolContract,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ToolContract:
        """Updates the details of the tool in the API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param tool_id: Tool identifier within an API. Must be unique in the current API Management
         service instance. Required.
        :type tool_id: str
        :param parameters: API Tool Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ToolContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ToolContract. The ToolContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ToolContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        tool_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ToolContract:
        """Updates the details of the tool in the API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param tool_id: Tool identifier within an API. Must be unique in the current API Management
         service instance. Required.
        :type tool_id: str
        :param parameters: API Tool Update parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ToolContract. The ToolContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ToolContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        tool_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ToolContract:
        """Updates the details of the tool in the API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param tool_id: Tool identifier within an API. Must be unique in the current API Management
         service instance. Required.
        :type tool_id: str
        :param parameters: API Tool Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ToolContract. The ToolContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ToolContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        tool_id: str,
        parameters: Union[_models.ToolContract, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.ToolContract:
        """Updates the details of the tool in the API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param tool_id: Tool identifier within an API. Must be unique in the current API Management
         service instance. Required.
        :type tool_id: str
        :param parameters: API Tool Update parameters. Is one of the following types: ToolContract,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ToolContract or JSON or IO[bytes]
        :return: ToolContract. The ToolContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ToolContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ToolContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_api_tool_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            tool_id=tool_id,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ToolContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self, resource_group_name: str, service_name: str, api_id: str, tool_id: str, **kwargs: Any
    ) -> None:
        """Deletes the specified tool in the API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :param tool_id: Tool identifier within an API. Must be unique in the current API Management
         service instance. Required.
        :type tool_id: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_api_tool_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            tool_id=tool_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_api(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.ToolContract"]:
        """Lists a collection of the MCP tools for the specified API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         description | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of ToolContract
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ToolContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ToolContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_api_tool_list_by_api_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    api_id=api_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ToolContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class ApiVersionSetOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`api_version_set` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, version_set_id: str, **kwargs: Any
    ) -> _models.ApiVersionSetContract:
        """Gets the details of the Api Version Set specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param version_set_id: Api Version Set identifier. Must be unique in the current API Management
         service instance. Required.
        :type version_set_id: str
        :return: ApiVersionSetContract. The ApiVersionSetContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiVersionSetContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ApiVersionSetContract] = kwargs.pop("cls", None)

        _request = build_api_version_set_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            version_set_id=version_set_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ApiVersionSetContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, version_set_id: str, **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the Api Version Set specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param version_set_id: Api Version Set identifier. Must be unique in the current API Management
         service instance. Required.
        :type version_set_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_api_version_set_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            version_set_id=version_set_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        version_set_id: str,
        parameters: _models.ApiVersionSetContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ApiVersionSetContract:
        """Creates or Updates a Api Version Set.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param version_set_id: Api Version Set identifier. Must be unique in the current API Management
         service instance. Required.
        :type version_set_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiVersionSetContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ApiVersionSetContract. The ApiVersionSetContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiVersionSetContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        version_set_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ApiVersionSetContract:
        """Creates or Updates a Api Version Set.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param version_set_id: Api Version Set identifier. Must be unique in the current API Management
         service instance. Required.
        :type version_set_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ApiVersionSetContract. The ApiVersionSetContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiVersionSetContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        version_set_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ApiVersionSetContract:
        """Creates or Updates a Api Version Set.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param version_set_id: Api Version Set identifier. Must be unique in the current API Management
         service instance. Required.
        :type version_set_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ApiVersionSetContract. The ApiVersionSetContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiVersionSetContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        version_set_id: str,
        parameters: Union[_models.ApiVersionSetContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ApiVersionSetContract:
        """Creates or Updates a Api Version Set.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param version_set_id: Api Version Set identifier. Must be unique in the current API Management
         service instance. Required.
        :type version_set_id: str
        :param parameters: Create or update parameters. Is one of the following types:
         ApiVersionSetContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiVersionSetContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ApiVersionSetContract. The ApiVersionSetContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiVersionSetContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ApiVersionSetContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_api_version_set_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            version_set_id=version_set_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ApiVersionSetContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        version_set_id: str,
        parameters: _models.ApiVersionSetUpdateParameters,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ApiVersionSetContract:
        """Updates the details of the Api VersionSet specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param version_set_id: Api Version Set identifier. Must be unique in the current API Management
         service instance. Required.
        :type version_set_id: str
        :param parameters: Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiVersionSetUpdateParameters
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ApiVersionSetContract. The ApiVersionSetContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiVersionSetContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        version_set_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ApiVersionSetContract:
        """Updates the details of the Api VersionSet specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param version_set_id: Api Version Set identifier. Must be unique in the current API Management
         service instance. Required.
        :type version_set_id: str
        :param parameters: Update parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ApiVersionSetContract. The ApiVersionSetContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiVersionSetContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        version_set_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ApiVersionSetContract:
        """Updates the details of the Api VersionSet specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param version_set_id: Api Version Set identifier. Must be unique in the current API Management
         service instance. Required.
        :type version_set_id: str
        :param parameters: Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ApiVersionSetContract. The ApiVersionSetContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiVersionSetContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        version_set_id: str,
        parameters: Union[_models.ApiVersionSetUpdateParameters, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.ApiVersionSetContract:
        """Updates the details of the Api VersionSet specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param version_set_id: Api Version Set identifier. Must be unique in the current API Management
         service instance. Required.
        :type version_set_id: str
        :param parameters: Update parameters. Is one of the following types:
         ApiVersionSetUpdateParameters, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiVersionSetUpdateParameters or JSON or
         IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ApiVersionSetContract. The ApiVersionSetContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiVersionSetContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ApiVersionSetContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_api_version_set_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            version_set_id=version_set_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ApiVersionSetContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        version_set_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes specific Api Version Set.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param version_set_id: Api Version Set identifier. Must be unique in the current API Management
         service instance. Required.
        :type version_set_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_api_version_set_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            version_set_id=version_set_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.ApiVersionSetContract"]:
        """Lists a collection of API Version Sets in the specified service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of ApiVersionSetContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ApiVersionSetContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ApiVersionSetContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_api_version_set_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ApiVersionSetContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class AuthorizationProviderOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`authorization_provider` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, authorization_provider_id: str, **kwargs: Any
    ) -> _models.AuthorizationProviderContract:
        """Gets the details of the authorization provider specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authorization_provider_id: Identifier of the authorization provider. Required.
        :type authorization_provider_id: str
        :return: AuthorizationProviderContract. The AuthorizationProviderContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AuthorizationProviderContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.AuthorizationProviderContract] = kwargs.pop("cls", None)

        _request = build_authorization_provider_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            authorization_provider_id=authorization_provider_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.AuthorizationProviderContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        authorization_provider_id: str,
        parameters: _models.AuthorizationProviderContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.AuthorizationProviderContract:
        """Creates or updates authorization provider.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authorization_provider_id: Identifier of the authorization provider. Required.
        :type authorization_provider_id: str
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.AuthorizationProviderContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: AuthorizationProviderContract. The AuthorizationProviderContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AuthorizationProviderContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        authorization_provider_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.AuthorizationProviderContract:
        """Creates or updates authorization provider.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authorization_provider_id: Identifier of the authorization provider. Required.
        :type authorization_provider_id: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: AuthorizationProviderContract. The AuthorizationProviderContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AuthorizationProviderContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        authorization_provider_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.AuthorizationProviderContract:
        """Creates or updates authorization provider.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authorization_provider_id: Identifier of the authorization provider. Required.
        :type authorization_provider_id: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: AuthorizationProviderContract. The AuthorizationProviderContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AuthorizationProviderContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        authorization_provider_id: str,
        parameters: Union[_models.AuthorizationProviderContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.AuthorizationProviderContract:
        """Creates or updates authorization provider.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authorization_provider_id: Identifier of the authorization provider. Required.
        :type authorization_provider_id: str
        :param parameters: Create parameters. Is one of the following types:
         AuthorizationProviderContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.AuthorizationProviderContract or JSON or
         IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: AuthorizationProviderContract. The AuthorizationProviderContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AuthorizationProviderContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.AuthorizationProviderContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_authorization_provider_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            authorization_provider_id=authorization_provider_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 200:
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if response.status_code == 201:
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.AuthorizationProviderContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        authorization_provider_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes specific authorization provider from the API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authorization_provider_id: Identifier of the authorization provider. Required.
        :type authorization_provider_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_authorization_provider_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            authorization_provider_id=authorization_provider_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.AuthorizationProviderContract"]:
        """Lists a collection of authorization providers defined within a service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         displayName | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of AuthorizationProviderContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.AuthorizationProviderContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.AuthorizationProviderContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_authorization_provider_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.AuthorizationProviderContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def refresh_secret(
        self, resource_group_name: str, service_name: str, authorization_provider_id: str, **kwargs: Any
    ) -> _models.AuthorizationProviderContract:
        """Refreshes the Key Vault reference secret for the specified authorization provider.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authorization_provider_id: Identifier of the authorization provider. Required.
        :type authorization_provider_id: str
        :return: AuthorizationProviderContract. The AuthorizationProviderContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AuthorizationProviderContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.AuthorizationProviderContract] = kwargs.pop("cls", None)

        _request = build_authorization_provider_refresh_secret_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            authorization_provider_id=authorization_provider_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.AuthorizationProviderContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore


class AuthorizationOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`authorization` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self,
        resource_group_name: str,
        service_name: str,
        authorization_provider_id: str,
        authorization_id: str,
        **kwargs: Any
    ) -> _models.AuthorizationContract:
        """Gets the details of the authorization specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authorization_provider_id: Identifier of the authorization provider. Required.
        :type authorization_provider_id: str
        :param authorization_id: Identifier of the authorization. Required.
        :type authorization_id: str
        :return: AuthorizationContract. The AuthorizationContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AuthorizationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.AuthorizationContract] = kwargs.pop("cls", None)

        _request = build_authorization_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            authorization_provider_id=authorization_provider_id,
            authorization_id=authorization_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.AuthorizationContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        authorization_provider_id: str,
        authorization_id: str,
        parameters: _models.AuthorizationContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.AuthorizationContract:
        """Creates or updates authorization.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authorization_provider_id: Identifier of the authorization provider. Required.
        :type authorization_provider_id: str
        :param authorization_id: Identifier of the authorization. Required.
        :type authorization_id: str
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.AuthorizationContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: AuthorizationContract. The AuthorizationContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AuthorizationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        authorization_provider_id: str,
        authorization_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.AuthorizationContract:
        """Creates or updates authorization.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authorization_provider_id: Identifier of the authorization provider. Required.
        :type authorization_provider_id: str
        :param authorization_id: Identifier of the authorization. Required.
        :type authorization_id: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: AuthorizationContract. The AuthorizationContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AuthorizationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        authorization_provider_id: str,
        authorization_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.AuthorizationContract:
        """Creates or updates authorization.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authorization_provider_id: Identifier of the authorization provider. Required.
        :type authorization_provider_id: str
        :param authorization_id: Identifier of the authorization. Required.
        :type authorization_id: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: AuthorizationContract. The AuthorizationContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AuthorizationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        authorization_provider_id: str,
        authorization_id: str,
        parameters: Union[_models.AuthorizationContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.AuthorizationContract:
        """Creates or updates authorization.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authorization_provider_id: Identifier of the authorization provider. Required.
        :type authorization_provider_id: str
        :param authorization_id: Identifier of the authorization. Required.
        :type authorization_id: str
        :param parameters: Create parameters. Is one of the following types: AuthorizationContract,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.AuthorizationContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: AuthorizationContract. The AuthorizationContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AuthorizationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.AuthorizationContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_authorization_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            authorization_provider_id=authorization_provider_id,
            authorization_id=authorization_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.AuthorizationContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        authorization_provider_id: str,
        authorization_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes specific Authorization from the Authorization provider.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authorization_provider_id: Identifier of the authorization provider. Required.
        :type authorization_provider_id: str
        :param authorization_id: Identifier of the authorization. Required.
        :type authorization_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_authorization_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            authorization_provider_id=authorization_provider_id,
            authorization_id=authorization_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_authorization_provider(
        self,
        resource_group_name: str,
        service_name: str,
        authorization_provider_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.AuthorizationContract"]:
        """Lists a collection of authorization providers defined within a authorization provider.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authorization_provider_id: Identifier of the authorization provider. Required.
        :type authorization_provider_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         displayName | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of AuthorizationContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.AuthorizationContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.AuthorizationContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_authorization_list_by_authorization_provider_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    authorization_provider_id=authorization_provider_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.AuthorizationContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @overload
    async def confirm_consent_code(
        self,
        resource_group_name: str,
        service_name: str,
        authorization_provider_id: str,
        authorization_id: str,
        parameters: _models.AuthorizationConfirmConsentCodeRequestContract,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> None:
        """Confirm valid consent code to suppress Authorizations anti-phishing page.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authorization_provider_id: Identifier of the authorization provider. Required.
        :type authorization_provider_id: str
        :param authorization_id: Identifier of the authorization. Required.
        :type authorization_id: str
        :param parameters: Create parameters. Required.
        :type parameters:
         ~azure.mgmt.apimanagement.models.AuthorizationConfirmConsentCodeRequestContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def confirm_consent_code(
        self,
        resource_group_name: str,
        service_name: str,
        authorization_provider_id: str,
        authorization_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> None:
        """Confirm valid consent code to suppress Authorizations anti-phishing page.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authorization_provider_id: Identifier of the authorization provider. Required.
        :type authorization_provider_id: str
        :param authorization_id: Identifier of the authorization. Required.
        :type authorization_id: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def confirm_consent_code(
        self,
        resource_group_name: str,
        service_name: str,
        authorization_provider_id: str,
        authorization_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> None:
        """Confirm valid consent code to suppress Authorizations anti-phishing page.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authorization_provider_id: Identifier of the authorization provider. Required.
        :type authorization_provider_id: str
        :param authorization_id: Identifier of the authorization. Required.
        :type authorization_id: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def confirm_consent_code(
        self,
        resource_group_name: str,
        service_name: str,
        authorization_provider_id: str,
        authorization_id: str,
        parameters: Union[_models.AuthorizationConfirmConsentCodeRequestContract, JSON, IO[bytes]],
        **kwargs: Any
    ) -> None:
        """Confirm valid consent code to suppress Authorizations anti-phishing page.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authorization_provider_id: Identifier of the authorization provider. Required.
        :type authorization_provider_id: str
        :param authorization_id: Identifier of the authorization. Required.
        :type authorization_id: str
        :param parameters: Create parameters. Is one of the following types:
         AuthorizationConfirmConsentCodeRequestContract, JSON, IO[bytes] Required.
        :type parameters:
         ~azure.mgmt.apimanagement.models.AuthorizationConfirmConsentCodeRequestContract or JSON or
         IO[bytes]
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[None] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_authorization_confirm_consent_code_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            authorization_provider_id=authorization_provider_id,
            authorization_id=authorization_id,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore


class AuthorizationLoginLinksOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`authorization_login_links` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @overload
    async def post(
        self,
        resource_group_name: str,
        service_name: str,
        authorization_provider_id: str,
        authorization_id: str,
        parameters: _models.AuthorizationLoginRequestContract,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.AuthorizationLoginResponseContract:
        """Gets authorization login links.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authorization_provider_id: Identifier of the authorization provider. Required.
        :type authorization_provider_id: str
        :param authorization_id: Identifier of the authorization. Required.
        :type authorization_id: str
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.AuthorizationLoginRequestContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: AuthorizationLoginResponseContract. The AuthorizationLoginResponseContract is
         compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AuthorizationLoginResponseContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def post(
        self,
        resource_group_name: str,
        service_name: str,
        authorization_provider_id: str,
        authorization_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.AuthorizationLoginResponseContract:
        """Gets authorization login links.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authorization_provider_id: Identifier of the authorization provider. Required.
        :type authorization_provider_id: str
        :param authorization_id: Identifier of the authorization. Required.
        :type authorization_id: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: AuthorizationLoginResponseContract. The AuthorizationLoginResponseContract is
         compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AuthorizationLoginResponseContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def post(
        self,
        resource_group_name: str,
        service_name: str,
        authorization_provider_id: str,
        authorization_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.AuthorizationLoginResponseContract:
        """Gets authorization login links.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authorization_provider_id: Identifier of the authorization provider. Required.
        :type authorization_provider_id: str
        :param authorization_id: Identifier of the authorization. Required.
        :type authorization_id: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: AuthorizationLoginResponseContract. The AuthorizationLoginResponseContract is
         compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AuthorizationLoginResponseContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def post(
        self,
        resource_group_name: str,
        service_name: str,
        authorization_provider_id: str,
        authorization_id: str,
        parameters: Union[_models.AuthorizationLoginRequestContract, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.AuthorizationLoginResponseContract:
        """Gets authorization login links.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authorization_provider_id: Identifier of the authorization provider. Required.
        :type authorization_provider_id: str
        :param authorization_id: Identifier of the authorization. Required.
        :type authorization_id: str
        :param parameters: Create parameters. Is one of the following types:
         AuthorizationLoginRequestContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.AuthorizationLoginRequestContract or JSON or
         IO[bytes]
        :return: AuthorizationLoginResponseContract. The AuthorizationLoginResponseContract is
         compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AuthorizationLoginResponseContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.AuthorizationLoginResponseContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_authorization_login_links_post_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            authorization_provider_id=authorization_provider_id,
            authorization_id=authorization_id,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.AuthorizationLoginResponseContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore


class AuthorizationAccessPolicyOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`authorization_access_policy` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self,
        resource_group_name: str,
        service_name: str,
        authorization_provider_id: str,
        authorization_id: str,
        authorization_access_policy_id: str,
        **kwargs: Any
    ) -> _models.AuthorizationAccessPolicyContract:
        """Gets the details of the authorization access policy specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authorization_provider_id: Identifier of the authorization provider. Required.
        :type authorization_provider_id: str
        :param authorization_id: Identifier of the authorization. Required.
        :type authorization_id: str
        :param authorization_access_policy_id: Identifier of the authorization access policy. Required.
        :type authorization_access_policy_id: str
        :return: AuthorizationAccessPolicyContract. The AuthorizationAccessPolicyContract is compatible
         with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AuthorizationAccessPolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.AuthorizationAccessPolicyContract] = kwargs.pop("cls", None)

        _request = build_authorization_access_policy_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            authorization_provider_id=authorization_provider_id,
            authorization_id=authorization_id,
            authorization_access_policy_id=authorization_access_policy_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.AuthorizationAccessPolicyContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        authorization_provider_id: str,
        authorization_id: str,
        authorization_access_policy_id: str,
        parameters: _models.AuthorizationAccessPolicyContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.AuthorizationAccessPolicyContract:
        """Creates or updates Authorization Access Policy.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authorization_provider_id: Identifier of the authorization provider. Required.
        :type authorization_provider_id: str
        :param authorization_id: Identifier of the authorization. Required.
        :type authorization_id: str
        :param authorization_access_policy_id: Identifier of the authorization access policy. Required.
        :type authorization_access_policy_id: str
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.AuthorizationAccessPolicyContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: AuthorizationAccessPolicyContract. The AuthorizationAccessPolicyContract is compatible
         with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AuthorizationAccessPolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        authorization_provider_id: str,
        authorization_id: str,
        authorization_access_policy_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.AuthorizationAccessPolicyContract:
        """Creates or updates Authorization Access Policy.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authorization_provider_id: Identifier of the authorization provider. Required.
        :type authorization_provider_id: str
        :param authorization_id: Identifier of the authorization. Required.
        :type authorization_id: str
        :param authorization_access_policy_id: Identifier of the authorization access policy. Required.
        :type authorization_access_policy_id: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: AuthorizationAccessPolicyContract. The AuthorizationAccessPolicyContract is compatible
         with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AuthorizationAccessPolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        authorization_provider_id: str,
        authorization_id: str,
        authorization_access_policy_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.AuthorizationAccessPolicyContract:
        """Creates or updates Authorization Access Policy.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authorization_provider_id: Identifier of the authorization provider. Required.
        :type authorization_provider_id: str
        :param authorization_id: Identifier of the authorization. Required.
        :type authorization_id: str
        :param authorization_access_policy_id: Identifier of the authorization access policy. Required.
        :type authorization_access_policy_id: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: AuthorizationAccessPolicyContract. The AuthorizationAccessPolicyContract is compatible
         with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AuthorizationAccessPolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        authorization_provider_id: str,
        authorization_id: str,
        authorization_access_policy_id: str,
        parameters: Union[_models.AuthorizationAccessPolicyContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.AuthorizationAccessPolicyContract:
        """Creates or updates Authorization Access Policy.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authorization_provider_id: Identifier of the authorization provider. Required.
        :type authorization_provider_id: str
        :param authorization_id: Identifier of the authorization. Required.
        :type authorization_id: str
        :param authorization_access_policy_id: Identifier of the authorization access policy. Required.
        :type authorization_access_policy_id: str
        :param parameters: Create parameters. Is one of the following types:
         AuthorizationAccessPolicyContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.AuthorizationAccessPolicyContract or JSON or
         IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: AuthorizationAccessPolicyContract. The AuthorizationAccessPolicyContract is compatible
         with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AuthorizationAccessPolicyContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.AuthorizationAccessPolicyContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_authorization_access_policy_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            authorization_provider_id=authorization_provider_id,
            authorization_id=authorization_id,
            authorization_access_policy_id=authorization_access_policy_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.AuthorizationAccessPolicyContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        authorization_provider_id: str,
        authorization_id: str,
        authorization_access_policy_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes specific access policy from the Authorization.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authorization_provider_id: Identifier of the authorization provider. Required.
        :type authorization_provider_id: str
        :param authorization_id: Identifier of the authorization. Required.
        :type authorization_id: str
        :param authorization_access_policy_id: Identifier of the authorization access policy. Required.
        :type authorization_access_policy_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_authorization_access_policy_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            authorization_provider_id=authorization_provider_id,
            authorization_id=authorization_id,
            authorization_access_policy_id=authorization_access_policy_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_authorization(
        self,
        resource_group_name: str,
        service_name: str,
        authorization_provider_id: str,
        authorization_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.AuthorizationAccessPolicyContract"]:
        """Lists a collection of authorization access policy defined within a authorization.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authorization_provider_id: Identifier of the authorization provider. Required.
        :type authorization_provider_id: str
        :param authorization_id: Identifier of the authorization. Required.
        :type authorization_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         displayName | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of AuthorizationAccessPolicyContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.AuthorizationAccessPolicyContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.AuthorizationAccessPolicyContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_authorization_access_policy_list_by_authorization_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    authorization_provider_id=authorization_provider_id,
                    authorization_id=authorization_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.AuthorizationAccessPolicyContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class AuthorizationServerOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`authorization_server` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, authsid: str, **kwargs: Any
    ) -> _models.AuthorizationServerContract:
        """Gets the details of the authorization server specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authsid: Identifier of the authorization server. Required.
        :type authsid: str
        :return: AuthorizationServerContract. The AuthorizationServerContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AuthorizationServerContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.AuthorizationServerContract] = kwargs.pop("cls", None)

        _request = build_authorization_server_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            authsid=authsid,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.AuthorizationServerContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(self, resource_group_name: str, service_name: str, authsid: str, **kwargs: Any) -> bool:
        """Gets the entity state (Etag) version of the authorizationServer specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authsid: Identifier of the authorization server. Required.
        :type authsid: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_authorization_server_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            authsid=authsid,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        authsid: str,
        parameters: _models.AuthorizationServerContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.AuthorizationServerContract:
        """Creates new authorization server or updates an existing authorization server.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authsid: Identifier of the authorization server. Required.
        :type authsid: str
        :param parameters: Create or update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.AuthorizationServerContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: AuthorizationServerContract. The AuthorizationServerContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AuthorizationServerContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        authsid: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.AuthorizationServerContract:
        """Creates new authorization server or updates an existing authorization server.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authsid: Identifier of the authorization server. Required.
        :type authsid: str
        :param parameters: Create or update parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: AuthorizationServerContract. The AuthorizationServerContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AuthorizationServerContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        authsid: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.AuthorizationServerContract:
        """Creates new authorization server or updates an existing authorization server.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authsid: Identifier of the authorization server. Required.
        :type authsid: str
        :param parameters: Create or update parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: AuthorizationServerContract. The AuthorizationServerContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AuthorizationServerContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        authsid: str,
        parameters: Union[_models.AuthorizationServerContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.AuthorizationServerContract:
        """Creates new authorization server or updates an existing authorization server.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authsid: Identifier of the authorization server. Required.
        :type authsid: str
        :param parameters: Create or update parameters. Is one of the following types:
         AuthorizationServerContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.AuthorizationServerContract or JSON or
         IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: AuthorizationServerContract. The AuthorizationServerContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AuthorizationServerContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.AuthorizationServerContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_authorization_server_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            authsid=authsid,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 200:
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if response.status_code == 201:
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.AuthorizationServerContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        authsid: str,
        parameters: _models.AuthorizationServerUpdateContract,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.AuthorizationServerContract:
        """Updates the details of the authorization server specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authsid: Identifier of the authorization server. Required.
        :type authsid: str
        :param parameters: OAuth2 Server settings Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.AuthorizationServerUpdateContract
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: AuthorizationServerContract. The AuthorizationServerContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AuthorizationServerContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        authsid: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.AuthorizationServerContract:
        """Updates the details of the authorization server specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authsid: Identifier of the authorization server. Required.
        :type authsid: str
        :param parameters: OAuth2 Server settings Update parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: AuthorizationServerContract. The AuthorizationServerContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AuthorizationServerContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        authsid: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.AuthorizationServerContract:
        """Updates the details of the authorization server specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authsid: Identifier of the authorization server. Required.
        :type authsid: str
        :param parameters: OAuth2 Server settings Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: AuthorizationServerContract. The AuthorizationServerContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AuthorizationServerContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        authsid: str,
        parameters: Union[_models.AuthorizationServerUpdateContract, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.AuthorizationServerContract:
        """Updates the details of the authorization server specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authsid: Identifier of the authorization server. Required.
        :type authsid: str
        :param parameters: OAuth2 Server settings Update parameters. Is one of the following types:
         AuthorizationServerUpdateContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.AuthorizationServerUpdateContract or JSON or
         IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: AuthorizationServerContract. The AuthorizationServerContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AuthorizationServerContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.AuthorizationServerContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_authorization_server_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            authsid=authsid,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.AuthorizationServerContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        authsid: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes specific authorization server instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authsid: Identifier of the authorization server. Required.
        :type authsid: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_authorization_server_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            authsid=authsid,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.AuthorizationServerContract"]:
        """Lists a collection of authorization servers defined within a service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         displayName | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of AuthorizationServerContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.AuthorizationServerContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.AuthorizationServerContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_authorization_server_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.AuthorizationServerContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def list_secrets(
        self, resource_group_name: str, service_name: str, authsid: str, **kwargs: Any
    ) -> _models.AuthorizationServerSecretsContract:
        """Gets the client secret details of the authorization server.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param authsid: Identifier of the authorization server. Required.
        :type authsid: str
        :return: AuthorizationServerSecretsContract. The AuthorizationServerSecretsContract is
         compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AuthorizationServerSecretsContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.AuthorizationServerSecretsContract] = kwargs.pop("cls", None)

        _request = build_authorization_server_list_secrets_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            authsid=authsid,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.AuthorizationServerSecretsContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore


class BackendOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`backend` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, backend_id: str, **kwargs: Any
    ) -> _models.BackendContract:
        """Gets the details of the backend specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param backend_id: Identifier of the Backend entity. Must be unique in the current API
         Management service instance. Required.
        :type backend_id: str
        :return: BackendContract. The BackendContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.BackendContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.BackendContract] = kwargs.pop("cls", None)

        _request = build_backend_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            backend_id=backend_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.BackendContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(self, resource_group_name: str, service_name: str, backend_id: str, **kwargs: Any) -> bool:
        """Gets the entity state (Etag) version of the backend specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param backend_id: Identifier of the Backend entity. Must be unique in the current API
         Management service instance. Required.
        :type backend_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_backend_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            backend_id=backend_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        backend_id: str,
        parameters: _models.BackendContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.BackendContract:
        """Creates or Updates a backend.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param backend_id: Identifier of the Backend entity. Must be unique in the current API
         Management service instance. Required.
        :type backend_id: str
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.BackendContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: BackendContract. The BackendContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.BackendContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        backend_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.BackendContract:
        """Creates or Updates a backend.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param backend_id: Identifier of the Backend entity. Must be unique in the current API
         Management service instance. Required.
        :type backend_id: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: BackendContract. The BackendContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.BackendContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        backend_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.BackendContract:
        """Creates or Updates a backend.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param backend_id: Identifier of the Backend entity. Must be unique in the current API
         Management service instance. Required.
        :type backend_id: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: BackendContract. The BackendContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.BackendContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        backend_id: str,
        parameters: Union[_models.BackendContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.BackendContract:
        """Creates or Updates a backend.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param backend_id: Identifier of the Backend entity. Must be unique in the current API
         Management service instance. Required.
        :type backend_id: str
        :param parameters: Create parameters. Is one of the following types: BackendContract, JSON,
         IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.BackendContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: BackendContract. The BackendContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.BackendContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.BackendContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_backend_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            backend_id=backend_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 200:
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if response.status_code == 201:
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.BackendContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        backend_id: str,
        parameters: _models.BackendUpdateParameters,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.BackendContract:
        """Updates an existing backend.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param backend_id: Identifier of the Backend entity. Must be unique in the current API
         Management service instance. Required.
        :type backend_id: str
        :param parameters: Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.BackendUpdateParameters
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: BackendContract. The BackendContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.BackendContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        backend_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.BackendContract:
        """Updates an existing backend.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param backend_id: Identifier of the Backend entity. Must be unique in the current API
         Management service instance. Required.
        :type backend_id: str
        :param parameters: Update parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: BackendContract. The BackendContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.BackendContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        backend_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.BackendContract:
        """Updates an existing backend.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param backend_id: Identifier of the Backend entity. Must be unique in the current API
         Management service instance. Required.
        :type backend_id: str
        :param parameters: Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: BackendContract. The BackendContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.BackendContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        backend_id: str,
        parameters: Union[_models.BackendUpdateParameters, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.BackendContract:
        """Updates an existing backend.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param backend_id: Identifier of the Backend entity. Must be unique in the current API
         Management service instance. Required.
        :type backend_id: str
        :param parameters: Update parameters. Is one of the following types: BackendUpdateParameters,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.BackendUpdateParameters or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: BackendContract. The BackendContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.BackendContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.BackendContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_backend_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            backend_id=backend_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.BackendContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        backend_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes the specified backend.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param backend_id: Identifier of the Backend entity. Must be unique in the current API
         Management service instance. Required.
        :type backend_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_backend_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            backend_id=backend_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.BackendContract"]:
        """Lists a collection of backends in the specified service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>| title |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>| url |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of BackendContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.BackendContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BackendContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_backend_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BackendContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @overload
    async def reconnect(
        self,
        resource_group_name: str,
        service_name: str,
        backend_id: str,
        parameters: Optional[_models.BackendReconnectContract] = None,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> None:
        """Notifies the API Management gateway to create a new connection to the backend after the
        specified timeout. If no timeout was specified, timeout of 2 minutes is used.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param backend_id: Identifier of the Backend entity. Must be unique in the current API
         Management service instance. Required.
        :type backend_id: str
        :param parameters: Reconnect request parameters. Default value is None.
        :type parameters: ~azure.mgmt.apimanagement.models.BackendReconnectContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def reconnect(
        self,
        resource_group_name: str,
        service_name: str,
        backend_id: str,
        parameters: Optional[JSON] = None,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> None:
        """Notifies the API Management gateway to create a new connection to the backend after the
        specified timeout. If no timeout was specified, timeout of 2 minutes is used.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param backend_id: Identifier of the Backend entity. Must be unique in the current API
         Management service instance. Required.
        :type backend_id: str
        :param parameters: Reconnect request parameters. Default value is None.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def reconnect(
        self,
        resource_group_name: str,
        service_name: str,
        backend_id: str,
        parameters: Optional[IO[bytes]] = None,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> None:
        """Notifies the API Management gateway to create a new connection to the backend after the
        specified timeout. If no timeout was specified, timeout of 2 minutes is used.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param backend_id: Identifier of the Backend entity. Must be unique in the current API
         Management service instance. Required.
        :type backend_id: str
        :param parameters: Reconnect request parameters. Default value is None.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def reconnect(
        self,
        resource_group_name: str,
        service_name: str,
        backend_id: str,
        parameters: Optional[Union[_models.BackendReconnectContract, JSON, IO[bytes]]] = None,
        **kwargs: Any
    ) -> None:
        """Notifies the API Management gateway to create a new connection to the backend after the
        specified timeout. If no timeout was specified, timeout of 2 minutes is used.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param backend_id: Identifier of the Backend entity. Must be unique in the current API
         Management service instance. Required.
        :type backend_id: str
        :param parameters: Reconnect request parameters. Is one of the following types:
         BackendReconnectContract, JSON, IO[bytes] Default value is None.
        :type parameters: ~azure.mgmt.apimanagement.models.BackendReconnectContract or JSON or
         IO[bytes]
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        content_type = content_type if parameters else None
        cls: ClsType[None] = kwargs.pop("cls", None)

        content_type = content_type or "application/json" if parameters else None
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            if parameters is not None:
                _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore
            else:
                _content = None

        _request = build_backend_reconnect_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            backend_id=backend_id,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [202]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore


class CacheOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`cache` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, cache_id: str, **kwargs: Any
    ) -> _models.CacheContract:
        """Gets the details of the Cache specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param cache_id: Identifier of the Cache entity. Cache identifier (should be either 'default'
         or valid Azure region identifier). Required.
        :type cache_id: str
        :return: CacheContract. The CacheContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.CacheContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.CacheContract] = kwargs.pop("cls", None)

        _request = build_cache_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            cache_id=cache_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.CacheContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(self, resource_group_name: str, service_name: str, cache_id: str, **kwargs: Any) -> bool:
        """Gets the entity state (Etag) version of the Cache specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param cache_id: Identifier of the Cache entity. Cache identifier (should be either 'default'
         or valid Azure region identifier). Required.
        :type cache_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_cache_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            cache_id=cache_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        cache_id: str,
        parameters: _models.CacheContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.CacheContract:
        """Creates or updates an External Cache to be used in Api Management instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param cache_id: Identifier of the Cache entity. Cache identifier (should be either 'default'
         or valid Azure region identifier). Required.
        :type cache_id: str
        :param parameters: Create or Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.CacheContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: CacheContract. The CacheContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.CacheContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        cache_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.CacheContract:
        """Creates or updates an External Cache to be used in Api Management instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param cache_id: Identifier of the Cache entity. Cache identifier (should be either 'default'
         or valid Azure region identifier). Required.
        :type cache_id: str
        :param parameters: Create or Update parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: CacheContract. The CacheContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.CacheContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        cache_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.CacheContract:
        """Creates or updates an External Cache to be used in Api Management instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param cache_id: Identifier of the Cache entity. Cache identifier (should be either 'default'
         or valid Azure region identifier). Required.
        :type cache_id: str
        :param parameters: Create or Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: CacheContract. The CacheContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.CacheContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        cache_id: str,
        parameters: Union[_models.CacheContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.CacheContract:
        """Creates or updates an External Cache to be used in Api Management instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param cache_id: Identifier of the Cache entity. Cache identifier (should be either 'default'
         or valid Azure region identifier). Required.
        :type cache_id: str
        :param parameters: Create or Update parameters. Is one of the following types: CacheContract,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.CacheContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: CacheContract. The CacheContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.CacheContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.CacheContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_cache_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            cache_id=cache_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.CacheContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        cache_id: str,
        parameters: _models.CacheUpdateParameters,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.CacheContract:
        """Updates the details of the cache specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param cache_id: Identifier of the Cache entity. Cache identifier (should be either 'default'
         or valid Azure region identifier). Required.
        :type cache_id: str
        :param parameters: Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.CacheUpdateParameters
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: CacheContract. The CacheContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.CacheContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        cache_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.CacheContract:
        """Updates the details of the cache specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param cache_id: Identifier of the Cache entity. Cache identifier (should be either 'default'
         or valid Azure region identifier). Required.
        :type cache_id: str
        :param parameters: Update parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: CacheContract. The CacheContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.CacheContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        cache_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.CacheContract:
        """Updates the details of the cache specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param cache_id: Identifier of the Cache entity. Cache identifier (should be either 'default'
         or valid Azure region identifier). Required.
        :type cache_id: str
        :param parameters: Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: CacheContract. The CacheContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.CacheContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        cache_id: str,
        parameters: Union[_models.CacheUpdateParameters, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.CacheContract:
        """Updates the details of the cache specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param cache_id: Identifier of the Cache entity. Cache identifier (should be either 'default'
         or valid Azure region identifier). Required.
        :type cache_id: str
        :param parameters: Update parameters. Is one of the following types: CacheUpdateParameters,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.CacheUpdateParameters or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: CacheContract. The CacheContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.CacheContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.CacheContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_cache_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            cache_id=cache_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.CacheContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        cache_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes specific Cache.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param cache_id: Identifier of the Cache entity. Cache identifier (should be either 'default'
         or valid Azure region identifier). Required.
        :type cache_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_cache_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            cache_id=cache_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.CacheContract"]:
        """Lists a collection of all external Caches in the specified service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of CacheContract
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.CacheContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.CacheContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_cache_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.CacheContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class CertificateOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`certificate` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, certificate_id: str, **kwargs: Any
    ) -> _models.CertificateContract:
        """Gets the details of the certificate specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param certificate_id: Identifier of the certificate entity. Must be unique in the current API
         Management service instance. Required.
        :type certificate_id: str
        :return: CertificateContract. The CertificateContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.CertificateContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.CertificateContract] = kwargs.pop("cls", None)

        _request = build_certificate_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            certificate_id=certificate_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.CertificateContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, certificate_id: str, **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the certificate specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param certificate_id: Identifier of the certificate entity. Must be unique in the current API
         Management service instance. Required.
        :type certificate_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_certificate_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            certificate_id=certificate_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        certificate_id: str,
        parameters: _models.CertificateCreateOrUpdateParameters,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.CertificateContract:
        """Creates or updates the certificate being used for authentication with the backend.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param certificate_id: Identifier of the certificate entity. Must be unique in the current API
         Management service instance. Required.
        :type certificate_id: str
        :param parameters: Create or Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.CertificateCreateOrUpdateParameters
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: CertificateContract. The CertificateContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.CertificateContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        certificate_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.CertificateContract:
        """Creates or updates the certificate being used for authentication with the backend.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param certificate_id: Identifier of the certificate entity. Must be unique in the current API
         Management service instance. Required.
        :type certificate_id: str
        :param parameters: Create or Update parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: CertificateContract. The CertificateContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.CertificateContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        certificate_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.CertificateContract:
        """Creates or updates the certificate being used for authentication with the backend.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param certificate_id: Identifier of the certificate entity. Must be unique in the current API
         Management service instance. Required.
        :type certificate_id: str
        :param parameters: Create or Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: CertificateContract. The CertificateContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.CertificateContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        certificate_id: str,
        parameters: Union[_models.CertificateCreateOrUpdateParameters, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.CertificateContract:
        """Creates or updates the certificate being used for authentication with the backend.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param certificate_id: Identifier of the certificate entity. Must be unique in the current API
         Management service instance. Required.
        :type certificate_id: str
        :param parameters: Create or Update parameters. Is one of the following types:
         CertificateCreateOrUpdateParameters, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.CertificateCreateOrUpdateParameters or JSON
         or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: CertificateContract. The CertificateContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.CertificateContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.CertificateContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_certificate_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            certificate_id=certificate_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.CertificateContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        certificate_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes specific certificate.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param certificate_id: Identifier of the certificate entity. Must be unique in the current API
         Management service instance. Required.
        :type certificate_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_certificate_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            certificate_id=certificate_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        is_key_vault_refresh_failed: Optional[bool] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.CertificateContract"]:
        """Lists a collection of all certificates in the specified service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>| subject |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         thumbprint | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>| expirationDate | filter | ge, le, eq, ne, gt, lt |     |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :keyword is_key_vault_refresh_failed: When set to true, the response contains only certificates
         entities which failed refresh. Default value is None.
        :paramtype is_key_vault_refresh_failed: bool
        :return: An iterator like instance of CertificateContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.CertificateContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.CertificateContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_certificate_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    is_key_vault_refresh_failed=is_key_vault_refresh_failed,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.CertificateContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def refresh_secret(
        self, resource_group_name: str, service_name: str, certificate_id: str, **kwargs: Any
    ) -> _models.CertificateContract:
        """From KeyVault, Refresh the certificate being used for authentication with the backend.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param certificate_id: Identifier of the certificate entity. Must be unique in the current API
         Management service instance. Required.
        :type certificate_id: str
        :return: CertificateContract. The CertificateContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.CertificateContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.CertificateContract] = kwargs.pop("cls", None)

        _request = build_certificate_refresh_secret_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            certificate_id=certificate_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.CertificateContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore


class ContentTypeOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`content_type` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, content_type_id: str, **kwargs: Any
    ) -> _models.ContentTypeContract:
        """Gets the details of the developer portal's content type. Content types describe content items'
        properties, validation rules, and constraints.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param content_type_id: Content type identifier. Required.
        :type content_type_id: str
        :return: ContentTypeContract. The ContentTypeContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ContentTypeContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ContentTypeContract] = kwargs.pop("cls", None)

        _request = build_content_type_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            content_type_id=content_type_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ContentTypeContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        content_type_id: str,
        parameters: _models.ContentTypeContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ContentTypeContract:
        """Creates or updates the developer portal's content type. Content types describe content items'
        properties, validation rules, and constraints. Custom content types' identifiers need to start
        with the ``c-`` prefix. Built-in content types can't be modified.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param content_type_id: Content type identifier. Required.
        :type content_type_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ContentTypeContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ContentTypeContract. The ContentTypeContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ContentTypeContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        content_type_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ContentTypeContract:
        """Creates or updates the developer portal's content type. Content types describe content items'
        properties, validation rules, and constraints. Custom content types' identifiers need to start
        with the ``c-`` prefix. Built-in content types can't be modified.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param content_type_id: Content type identifier. Required.
        :type content_type_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ContentTypeContract. The ContentTypeContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ContentTypeContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        content_type_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ContentTypeContract:
        """Creates or updates the developer portal's content type. Content types describe content items'
        properties, validation rules, and constraints. Custom content types' identifiers need to start
        with the ``c-`` prefix. Built-in content types can't be modified.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param content_type_id: Content type identifier. Required.
        :type content_type_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ContentTypeContract. The ContentTypeContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ContentTypeContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        content_type_id: str,
        parameters: Union[_models.ContentTypeContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ContentTypeContract:
        """Creates or updates the developer portal's content type. Content types describe content items'
        properties, validation rules, and constraints. Custom content types' identifiers need to start
        with the ``c-`` prefix. Built-in content types can't be modified.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param content_type_id: Content type identifier. Required.
        :type content_type_id: str
        :param parameters: Create or update parameters. Is one of the following types:
         ContentTypeContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ContentTypeContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ContentTypeContract. The ContentTypeContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ContentTypeContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ContentTypeContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_content_type_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            content_type_id=content_type_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ContentTypeContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        content_type_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Removes the specified developer portal's content type. Content types describe content items'
        properties, validation rules, and constraints. Built-in content types (with identifiers
        starting with the ``c-`` prefix) can't be removed.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param content_type_id: Content type identifier. Required.
        :type content_type_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_content_type_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            content_type_id=content_type_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self, resource_group_name: str, service_name: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.ContentTypeContract"]:
        """Lists the developer portal's content types. Content types describe content items' properties,
        validation rules, and constraints.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :return: An iterator like instance of ContentTypeContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ContentTypeContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ContentTypeContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_content_type_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ContentTypeContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class ContentItemOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`content_item` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, content_type_id: str, content_item_id: str, **kwargs: Any
    ) -> _models.ContentItemContract:
        """Returns the developer portal's content item specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param content_type_id: Content type identifier. Required.
        :type content_type_id: str
        :param content_item_id: Content item identifier. Required.
        :type content_item_id: str
        :return: ContentItemContract. The ContentItemContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ContentItemContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ContentItemContract] = kwargs.pop("cls", None)

        _request = build_content_item_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            content_type_id=content_type_id,
            content_item_id=content_item_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ContentItemContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, content_type_id: str, content_item_id: str, **kwargs: Any
    ) -> bool:
        """Returns the entity state (ETag) version of the developer portal's content item specified by its
        identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param content_type_id: Content type identifier. Required.
        :type content_type_id: str
        :param content_item_id: Content item identifier. Required.
        :type content_item_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_content_item_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            content_type_id=content_type_id,
            content_item_id=content_item_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        content_type_id: str,
        content_item_id: str,
        parameters: _models.ContentItemContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ContentItemContract:
        """Creates a new developer portal's content item specified by the provided content type.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param content_type_id: Content type identifier. Required.
        :type content_type_id: str
        :param content_item_id: Content item identifier. Required.
        :type content_item_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ContentItemContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ContentItemContract. The ContentItemContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ContentItemContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        content_type_id: str,
        content_item_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ContentItemContract:
        """Creates a new developer portal's content item specified by the provided content type.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param content_type_id: Content type identifier. Required.
        :type content_type_id: str
        :param content_item_id: Content item identifier. Required.
        :type content_item_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ContentItemContract. The ContentItemContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ContentItemContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        content_type_id: str,
        content_item_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ContentItemContract:
        """Creates a new developer portal's content item specified by the provided content type.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param content_type_id: Content type identifier. Required.
        :type content_type_id: str
        :param content_item_id: Content item identifier. Required.
        :type content_item_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ContentItemContract. The ContentItemContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ContentItemContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        content_type_id: str,
        content_item_id: str,
        parameters: Union[_models.ContentItemContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ContentItemContract:
        """Creates a new developer portal's content item specified by the provided content type.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param content_type_id: Content type identifier. Required.
        :type content_type_id: str
        :param content_item_id: Content item identifier. Required.
        :type content_item_id: str
        :param parameters: Create or update parameters. Is one of the following types:
         ContentItemContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ContentItemContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ContentItemContract. The ContentItemContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ContentItemContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ContentItemContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_content_item_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            content_type_id=content_type_id,
            content_item_id=content_item_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ContentItemContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        content_type_id: str,
        content_item_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Removes the specified developer portal's content item.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param content_type_id: Content type identifier. Required.
        :type content_type_id: str
        :param content_item_id: Content item identifier. Required.
        :type content_item_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_content_item_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            content_type_id=content_type_id,
            content_item_id=content_item_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self, resource_group_name: str, service_name: str, content_type_id: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.ContentItemContract"]:
        """Lists developer portal's content items specified by the provided content type.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param content_type_id: Content type identifier. Required.
        :type content_type_id: str
        :return: An iterator like instance of ContentItemContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ContentItemContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ContentItemContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_content_item_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    content_type_id=content_type_id,
                    subscription_id=self._config.subscription_id,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ContentItemContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class DeletedServicesOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`deleted_services` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get_by_name(self, service_name: str, location: str, **kwargs: Any) -> _models.DeletedServiceContract:
        """Get soft-deleted Api Management Service by name.

        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param location: The name of the Azure region. Required.
        :type location: str
        :return: DeletedServiceContract. The DeletedServiceContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DeletedServiceContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.DeletedServiceContract] = kwargs.pop("cls", None)

        _request = build_deleted_services_get_by_name_request(
            service_name=service_name,
            location=location,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.DeletedServiceContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    async def _purge_initial(self, service_name: str, location: str, **kwargs: Any) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        _request = build_deleted_services_purge_request(
            service_name=service_name,
            location=location,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202, 204]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def begin_purge(
        self, service_name: str, location: str, **kwargs: Any
    ) -> AsyncLROPoller[_models.DeletedServiceContract]:
        """Purges Api Management Service (deletes it with no option to undelete).

        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param location: The name of the Azure region. Required.
        :type location: str
        :return: An instance of AsyncLROPoller that returns DeletedServiceContract. The
         DeletedServiceContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.DeletedServiceContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.DeletedServiceContract] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._purge_initial(
                service_name=service_name,
                location=location,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.DeletedServiceContract, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.DeletedServiceContract].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.DeletedServiceContract](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @distributed_trace
    def list_by_subscription(self, **kwargs: Any) -> AsyncItemPaged["_models.DeletedServiceContract"]:
        """Lists all soft-deleted services available for undelete for the given subscription.

        :return: An iterator like instance of DeletedServiceContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.DeletedServiceContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.DeletedServiceContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_deleted_services_list_by_subscription_request(
                    subscription_id=self._config.subscription_id,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.DeletedServiceContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class DocumentationOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`documentation` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, documentation_id: str, **kwargs: Any
    ) -> _models.DocumentationContract:
        """Gets the details of the Documentation specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param documentation_id: Documentation identifier. Must be unique in the current API Management
         service instance. Required.
        :type documentation_id: str
        :return: DocumentationContract. The DocumentationContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DocumentationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.DocumentationContract] = kwargs.pop("cls", None)

        _request = build_documentation_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            documentation_id=documentation_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.DocumentationContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, documentation_id: str, **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the Documentation by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param documentation_id: Documentation identifier. Must be unique in the current API Management
         service instance. Required.
        :type documentation_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_documentation_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            documentation_id=documentation_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        documentation_id: str,
        parameters: _models.DocumentationContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.DocumentationContract:
        """Creates a new Documentation or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param documentation_id: Documentation identifier. Must be unique in the current API Management
         service instance. Required.
        :type documentation_id: str
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.DocumentationContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: DocumentationContract. The DocumentationContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DocumentationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        documentation_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.DocumentationContract:
        """Creates a new Documentation or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param documentation_id: Documentation identifier. Must be unique in the current API Management
         service instance. Required.
        :type documentation_id: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: DocumentationContract. The DocumentationContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DocumentationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        documentation_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.DocumentationContract:
        """Creates a new Documentation or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param documentation_id: Documentation identifier. Must be unique in the current API Management
         service instance. Required.
        :type documentation_id: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: DocumentationContract. The DocumentationContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DocumentationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        documentation_id: str,
        parameters: Union[_models.DocumentationContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.DocumentationContract:
        """Creates a new Documentation or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param documentation_id: Documentation identifier. Must be unique in the current API Management
         service instance. Required.
        :type documentation_id: str
        :param parameters: Create parameters. Is one of the following types: DocumentationContract,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.DocumentationContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: DocumentationContract. The DocumentationContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DocumentationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.DocumentationContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_documentation_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            documentation_id=documentation_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.DocumentationContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        documentation_id: str,
        parameters: _models.DocumentationUpdateContract,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.DocumentationContract:
        """Updates the details of the Documentation for an API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param documentation_id: Documentation identifier. Must be unique in the current API Management
         service instance. Required.
        :type documentation_id: str
        :param parameters: Documentation Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.DocumentationUpdateContract
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: DocumentationContract. The DocumentationContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DocumentationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        documentation_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.DocumentationContract:
        """Updates the details of the Documentation for an API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param documentation_id: Documentation identifier. Must be unique in the current API Management
         service instance. Required.
        :type documentation_id: str
        :param parameters: Documentation Update parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: DocumentationContract. The DocumentationContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DocumentationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        documentation_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.DocumentationContract:
        """Updates the details of the Documentation for an API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param documentation_id: Documentation identifier. Must be unique in the current API Management
         service instance. Required.
        :type documentation_id: str
        :param parameters: Documentation Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: DocumentationContract. The DocumentationContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DocumentationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        documentation_id: str,
        parameters: Union[_models.DocumentationUpdateContract, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.DocumentationContract:
        """Updates the details of the Documentation for an API specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param documentation_id: Documentation identifier. Must be unique in the current API Management
         service instance. Required.
        :type documentation_id: str
        :param parameters: Documentation Update parameters. Is one of the following types:
         DocumentationUpdateContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.DocumentationUpdateContract or JSON or
         IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: DocumentationContract. The DocumentationContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.DocumentationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.DocumentationContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_documentation_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            documentation_id=documentation_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.DocumentationContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        documentation_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes the specified Documentation from an API.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param documentation_id: Documentation identifier. Must be unique in the current API Management
         service instance. Required.
        :type documentation_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_documentation_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            documentation_id=documentation_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.DocumentationContract"]:
        """Lists all Documentations of the API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | eq |  contains |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of DocumentationContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.DocumentationContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.DocumentationContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_documentation_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.DocumentationContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class EmailTemplateOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`email_template` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self,
        resource_group_name: str,
        service_name: str,
        template_name: Union[str, _models.TemplateName],
        **kwargs: Any
    ) -> _models.EmailTemplateContract:
        """Gets the details of the email template specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param template_name: Email Template Name Identifier. Known values are:
         "applicationApprovedNotificationMessage", "accountClosedDeveloper",
         "quotaLimitApproachingDeveloperNotificationMessage", "newDeveloperNotificationMessage",
         "emailChangeIdentityDefault", "inviteUserNotificationMessage", "newCommentNotificationMessage",
         "confirmSignUpIdentityDefault", "newIssueNotificationMessage",
         "purchaseDeveloperNotificationMessage", "passwordResetIdentityDefault",
         "passwordResetByAdminNotificationMessage", "rejectDeveloperNotificationMessage", and
         "requestDeveloperNotificationMessage". Required.
        :type template_name: str or ~azure.mgmt.apimanagement.models.TemplateName
        :return: EmailTemplateContract. The EmailTemplateContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.EmailTemplateContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.EmailTemplateContract] = kwargs.pop("cls", None)

        _request = build_email_template_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            template_name=template_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.EmailTemplateContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self,
        resource_group_name: str,
        service_name: str,
        template_name: Union[str, _models.TemplateName],
        **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the email template specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param template_name: Email Template Name Identifier. Known values are:
         "applicationApprovedNotificationMessage", "accountClosedDeveloper",
         "quotaLimitApproachingDeveloperNotificationMessage", "newDeveloperNotificationMessage",
         "emailChangeIdentityDefault", "inviteUserNotificationMessage", "newCommentNotificationMessage",
         "confirmSignUpIdentityDefault", "newIssueNotificationMessage",
         "purchaseDeveloperNotificationMessage", "passwordResetIdentityDefault",
         "passwordResetByAdminNotificationMessage", "rejectDeveloperNotificationMessage", and
         "requestDeveloperNotificationMessage". Required.
        :type template_name: str or ~azure.mgmt.apimanagement.models.TemplateName
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_email_template_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            template_name=template_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        template_name: Union[str, _models.TemplateName],
        parameters: _models.EmailTemplateUpdateParameters,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.EmailTemplateContract:
        """Updates an Email Template.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param template_name: API revision identifier. Must be unique in the current API Management
         service instance. Non-current revision has ;rev=n as a suffix where n is the revision number.
         Known values are: "applicationApprovedNotificationMessage", "accountClosedDeveloper",
         "quotaLimitApproachingDeveloperNotificationMessage", "newDeveloperNotificationMessage",
         "emailChangeIdentityDefault", "inviteUserNotificationMessage", "newCommentNotificationMessage",
         "confirmSignUpIdentityDefault", "newIssueNotificationMessage",
         "purchaseDeveloperNotificationMessage", "passwordResetIdentityDefault",
         "passwordResetByAdminNotificationMessage", "rejectDeveloperNotificationMessage", and
         "requestDeveloperNotificationMessage". Required.
        :type template_name: str or ~azure.mgmt.apimanagement.models.TemplateName
        :param parameters: Email Template update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.EmailTemplateUpdateParameters
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: EmailTemplateContract. The EmailTemplateContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.EmailTemplateContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        template_name: Union[str, _models.TemplateName],
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.EmailTemplateContract:
        """Updates an Email Template.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param template_name: API revision identifier. Must be unique in the current API Management
         service instance. Non-current revision has ;rev=n as a suffix where n is the revision number.
         Known values are: "applicationApprovedNotificationMessage", "accountClosedDeveloper",
         "quotaLimitApproachingDeveloperNotificationMessage", "newDeveloperNotificationMessage",
         "emailChangeIdentityDefault", "inviteUserNotificationMessage", "newCommentNotificationMessage",
         "confirmSignUpIdentityDefault", "newIssueNotificationMessage",
         "purchaseDeveloperNotificationMessage", "passwordResetIdentityDefault",
         "passwordResetByAdminNotificationMessage", "rejectDeveloperNotificationMessage", and
         "requestDeveloperNotificationMessage". Required.
        :type template_name: str or ~azure.mgmt.apimanagement.models.TemplateName
        :param parameters: Email Template update parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: EmailTemplateContract. The EmailTemplateContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.EmailTemplateContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        template_name: Union[str, _models.TemplateName],
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.EmailTemplateContract:
        """Updates an Email Template.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param template_name: API revision identifier. Must be unique in the current API Management
         service instance. Non-current revision has ;rev=n as a suffix where n is the revision number.
         Known values are: "applicationApprovedNotificationMessage", "accountClosedDeveloper",
         "quotaLimitApproachingDeveloperNotificationMessage", "newDeveloperNotificationMessage",
         "emailChangeIdentityDefault", "inviteUserNotificationMessage", "newCommentNotificationMessage",
         "confirmSignUpIdentityDefault", "newIssueNotificationMessage",
         "purchaseDeveloperNotificationMessage", "passwordResetIdentityDefault",
         "passwordResetByAdminNotificationMessage", "rejectDeveloperNotificationMessage", and
         "requestDeveloperNotificationMessage". Required.
        :type template_name: str or ~azure.mgmt.apimanagement.models.TemplateName
        :param parameters: Email Template update parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: EmailTemplateContract. The EmailTemplateContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.EmailTemplateContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        template_name: Union[str, _models.TemplateName],
        parameters: Union[_models.EmailTemplateUpdateParameters, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.EmailTemplateContract:
        """Updates an Email Template.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param template_name: API revision identifier. Must be unique in the current API Management
         service instance. Non-current revision has ;rev=n as a suffix where n is the revision number.
         Known values are: "applicationApprovedNotificationMessage", "accountClosedDeveloper",
         "quotaLimitApproachingDeveloperNotificationMessage", "newDeveloperNotificationMessage",
         "emailChangeIdentityDefault", "inviteUserNotificationMessage", "newCommentNotificationMessage",
         "confirmSignUpIdentityDefault", "newIssueNotificationMessage",
         "purchaseDeveloperNotificationMessage", "passwordResetIdentityDefault",
         "passwordResetByAdminNotificationMessage", "rejectDeveloperNotificationMessage", and
         "requestDeveloperNotificationMessage". Required.
        :type template_name: str or ~azure.mgmt.apimanagement.models.TemplateName
        :param parameters: Email Template update parameters. Is one of the following types:
         EmailTemplateUpdateParameters, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.EmailTemplateUpdateParameters or JSON or
         IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: EmailTemplateContract. The EmailTemplateContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.EmailTemplateContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.EmailTemplateContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_email_template_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            template_name=template_name,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.EmailTemplateContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        template_name: Union[str, _models.TemplateName],
        parameters: _models.EmailTemplateUpdateParameters,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.EmailTemplateContract:
        """Updates API Management email template.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param template_name: Email Template Name Identifier. Known values are:
         "applicationApprovedNotificationMessage", "accountClosedDeveloper",
         "quotaLimitApproachingDeveloperNotificationMessage", "newDeveloperNotificationMessage",
         "emailChangeIdentityDefault", "inviteUserNotificationMessage", "newCommentNotificationMessage",
         "confirmSignUpIdentityDefault", "newIssueNotificationMessage",
         "purchaseDeveloperNotificationMessage", "passwordResetIdentityDefault",
         "passwordResetByAdminNotificationMessage", "rejectDeveloperNotificationMessage", and
         "requestDeveloperNotificationMessage". Required.
        :type template_name: str or ~azure.mgmt.apimanagement.models.TemplateName
        :param parameters: Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.EmailTemplateUpdateParameters
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: EmailTemplateContract. The EmailTemplateContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.EmailTemplateContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        template_name: Union[str, _models.TemplateName],
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.EmailTemplateContract:
        """Updates API Management email template.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param template_name: Email Template Name Identifier. Known values are:
         "applicationApprovedNotificationMessage", "accountClosedDeveloper",
         "quotaLimitApproachingDeveloperNotificationMessage", "newDeveloperNotificationMessage",
         "emailChangeIdentityDefault", "inviteUserNotificationMessage", "newCommentNotificationMessage",
         "confirmSignUpIdentityDefault", "newIssueNotificationMessage",
         "purchaseDeveloperNotificationMessage", "passwordResetIdentityDefault",
         "passwordResetByAdminNotificationMessage", "rejectDeveloperNotificationMessage", and
         "requestDeveloperNotificationMessage". Required.
        :type template_name: str or ~azure.mgmt.apimanagement.models.TemplateName
        :param parameters: Update parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: EmailTemplateContract. The EmailTemplateContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.EmailTemplateContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        template_name: Union[str, _models.TemplateName],
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.EmailTemplateContract:
        """Updates API Management email template.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param template_name: Email Template Name Identifier. Known values are:
         "applicationApprovedNotificationMessage", "accountClosedDeveloper",
         "quotaLimitApproachingDeveloperNotificationMessage", "newDeveloperNotificationMessage",
         "emailChangeIdentityDefault", "inviteUserNotificationMessage", "newCommentNotificationMessage",
         "confirmSignUpIdentityDefault", "newIssueNotificationMessage",
         "purchaseDeveloperNotificationMessage", "passwordResetIdentityDefault",
         "passwordResetByAdminNotificationMessage", "rejectDeveloperNotificationMessage", and
         "requestDeveloperNotificationMessage". Required.
        :type template_name: str or ~azure.mgmt.apimanagement.models.TemplateName
        :param parameters: Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: EmailTemplateContract. The EmailTemplateContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.EmailTemplateContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        template_name: Union[str, _models.TemplateName],
        parameters: Union[_models.EmailTemplateUpdateParameters, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.EmailTemplateContract:
        """Updates API Management email template.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param template_name: Email Template Name Identifier. Known values are:
         "applicationApprovedNotificationMessage", "accountClosedDeveloper",
         "quotaLimitApproachingDeveloperNotificationMessage", "newDeveloperNotificationMessage",
         "emailChangeIdentityDefault", "inviteUserNotificationMessage", "newCommentNotificationMessage",
         "confirmSignUpIdentityDefault", "newIssueNotificationMessage",
         "purchaseDeveloperNotificationMessage", "passwordResetIdentityDefault",
         "passwordResetByAdminNotificationMessage", "rejectDeveloperNotificationMessage", and
         "requestDeveloperNotificationMessage". Required.
        :type template_name: str or ~azure.mgmt.apimanagement.models.TemplateName
        :param parameters: Update parameters. Is one of the following types:
         EmailTemplateUpdateParameters, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.EmailTemplateUpdateParameters or JSON or
         IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: EmailTemplateContract. The EmailTemplateContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.EmailTemplateContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.EmailTemplateContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_email_template_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            template_name=template_name,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.EmailTemplateContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        template_name: Union[str, _models.TemplateName],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Reset the Email Template to default template provided by the API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param template_name: Email Template Name Identifier. Known values are:
         "applicationApprovedNotificationMessage", "accountClosedDeveloper",
         "quotaLimitApproachingDeveloperNotificationMessage", "newDeveloperNotificationMessage",
         "emailChangeIdentityDefault", "inviteUserNotificationMessage", "newCommentNotificationMessage",
         "confirmSignUpIdentityDefault", "newIssueNotificationMessage",
         "purchaseDeveloperNotificationMessage", "passwordResetIdentityDefault",
         "passwordResetByAdminNotificationMessage", "rejectDeveloperNotificationMessage", and
         "requestDeveloperNotificationMessage". Required.
        :type template_name: str or ~azure.mgmt.apimanagement.models.TemplateName
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_email_template_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            template_name=template_name,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.EmailTemplateContract"]:
        """Gets all email templates.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of EmailTemplateContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.EmailTemplateContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.EmailTemplateContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_email_template_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.EmailTemplateContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class ApiGatewayConfigConnectionOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`api_gateway_config_connection` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, gateway_name: str, config_connection_name: str, **kwargs: Any
    ) -> _models.ApiManagementGatewayConfigConnectionResource:
        """Gets an API Management gateway config connection resource description.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param gateway_name: The name of the API Management gateway. Required.
        :type gateway_name: str
        :param config_connection_name: The name of the API Management gateway config connection.
         Required.
        :type config_connection_name: str
        :return: ApiManagementGatewayConfigConnectionResource. The
         ApiManagementGatewayConfigConnectionResource is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiManagementGatewayConfigConnectionResource
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ApiManagementGatewayConfigConnectionResource] = kwargs.pop("cls", None)

        _request = build_api_gateway_config_connection_get_request(
            resource_group_name=resource_group_name,
            gateway_name=gateway_name,
            config_connection_name=config_connection_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ApiManagementGatewayConfigConnectionResource, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    async def _create_or_update_initial(
        self,
        resource_group_name: str,
        gateway_name: str,
        config_connection_name: str,
        parameters: Union[_models.ApiManagementGatewayConfigConnectionResource, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_api_gateway_config_connection_create_or_update_request(
            resource_group_name=resource_group_name,
            gateway_name=gateway_name,
            config_connection_name=config_connection_name,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 201:
            response_headers["Azure-AsyncOperation"] = self._deserialize(
                "str", response.headers.get("Azure-AsyncOperation")
            )
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        gateway_name: str,
        config_connection_name: str,
        parameters: _models.ApiManagementGatewayConfigConnectionResource,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementGatewayConfigConnectionResource]:
        """Creates or updates an API Management gateway config connection. This is long running operation
        and could take several minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param gateway_name: The name of the API Management gateway. Required.
        :type gateway_name: str
        :param config_connection_name: The name of the API Management gateway config connection.
         Required.
        :type config_connection_name: str
        :param parameters: Parameters supplied to the CreateOrUpdate API Management gateway config
         connection operation. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiManagementGatewayConfigConnectionResource
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns
         ApiManagementGatewayConfigConnectionResource. The ApiManagementGatewayConfigConnectionResource
         is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementGatewayConfigConnectionResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        gateway_name: str,
        config_connection_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementGatewayConfigConnectionResource]:
        """Creates or updates an API Management gateway config connection. This is long running operation
        and could take several minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param gateway_name: The name of the API Management gateway. Required.
        :type gateway_name: str
        :param config_connection_name: The name of the API Management gateway config connection.
         Required.
        :type config_connection_name: str
        :param parameters: Parameters supplied to the CreateOrUpdate API Management gateway config
         connection operation. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns
         ApiManagementGatewayConfigConnectionResource. The ApiManagementGatewayConfigConnectionResource
         is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementGatewayConfigConnectionResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        gateway_name: str,
        config_connection_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementGatewayConfigConnectionResource]:
        """Creates or updates an API Management gateway config connection. This is long running operation
        and could take several minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param gateway_name: The name of the API Management gateway. Required.
        :type gateway_name: str
        :param config_connection_name: The name of the API Management gateway config connection.
         Required.
        :type config_connection_name: str
        :param parameters: Parameters supplied to the CreateOrUpdate API Management gateway config
         connection operation. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns
         ApiManagementGatewayConfigConnectionResource. The ApiManagementGatewayConfigConnectionResource
         is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementGatewayConfigConnectionResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        gateway_name: str,
        config_connection_name: str,
        parameters: Union[_models.ApiManagementGatewayConfigConnectionResource, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ApiManagementGatewayConfigConnectionResource]:
        """Creates or updates an API Management gateway config connection. This is long running operation
        and could take several minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param gateway_name: The name of the API Management gateway. Required.
        :type gateway_name: str
        :param config_connection_name: The name of the API Management gateway config connection.
         Required.
        :type config_connection_name: str
        :param parameters: Parameters supplied to the CreateOrUpdate API Management gateway config
         connection operation. Is one of the following types:
         ApiManagementGatewayConfigConnectionResource, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ApiManagementGatewayConfigConnectionResource
         or JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns
         ApiManagementGatewayConfigConnectionResource. The ApiManagementGatewayConfigConnectionResource
         is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ApiManagementGatewayConfigConnectionResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ApiManagementGatewayConfigConnectionResource] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._create_or_update_initial(
                resource_group_name=resource_group_name,
                gateway_name=gateway_name,
                config_connection_name=config_connection_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.ApiManagementGatewayConfigConnectionResource, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.ApiManagementGatewayConfigConnectionResource].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.ApiManagementGatewayConfigConnectionResource](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _delete_initial(
        self,
        resource_group_name: str,
        gateway_name: str,
        config_connection_name: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        _request = build_api_gateway_config_connection_delete_request(
            resource_group_name=resource_group_name,
            gateway_name=gateway_name,
            config_connection_name=config_connection_name,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [202, 204]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def begin_delete(
        self,
        resource_group_name: str,
        gateway_name: str,
        config_connection_name: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> AsyncLROPoller[None]:
        """Deletes an existing API Management gateway config connection.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param gateway_name: The name of the API Management gateway. Required.
        :type gateway_name: str
        :param config_connection_name: The name of the API Management gateway config connection.
         Required.
        :type config_connection_name: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns None
        :rtype: ~azure.core.polling.AsyncLROPoller[None]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._delete_initial(
                resource_group_name=resource_group_name,
                gateway_name=gateway_name,
                config_connection_name=config_connection_name,
                etag=etag,
                match_condition=match_condition,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):  # pylint: disable=inconsistent-return-statements
            if cls:
                return cls(pipeline_response, None, {})  # type: ignore

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[None].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method)  # type: ignore

    @distributed_trace
    def list_by_gateway(
        self, resource_group_name: str, gateway_name: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.ApiManagementGatewayConfigConnectionResource"]:
        """List all API Management gateway config connections within a gateway.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param gateway_name: The name of the API Management gateway. Required.
        :type gateway_name: str
        :return: An iterator like instance of ApiManagementGatewayConfigConnectionResource
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ApiManagementGatewayConfigConnectionResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ApiManagementGatewayConfigConnectionResource]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_api_gateway_config_connection_list_by_gateway_request(
                    resource_group_name=resource_group_name,
                    gateway_name=gateway_name,
                    subscription_id=self._config.subscription_id,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ApiManagementGatewayConfigConnectionResource],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class ApiGatewayHostnameBindingOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`api_gateway_hostname_binding` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, gateway_name: str, hostname_binding_name: str, **kwargs: Any
    ) -> _models.GatewayHostnameBindingResource:
        """Gets an API Management gateway hostname binding resource description.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param gateway_name: The name of the API Management gateway. Required.
        :type gateway_name: str
        :param hostname_binding_name: Gateway hostname binding identifier. Must be unique in the scope
         of parent Gateway entity. Required.
        :type hostname_binding_name: str
        :return: GatewayHostnameBindingResource. The GatewayHostnameBindingResource is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GatewayHostnameBindingResource
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.GatewayHostnameBindingResource] = kwargs.pop("cls", None)

        _request = build_api_gateway_hostname_binding_get_request(
            resource_group_name=resource_group_name,
            gateway_name=gateway_name,
            hostname_binding_name=hostname_binding_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.GatewayHostnameBindingResource, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    async def _create_or_update_initial(
        self,
        resource_group_name: str,
        gateway_name: str,
        hostname_binding_name: str,
        parameters: Union[_models.GatewayHostnameBindingResource, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_api_gateway_hostname_binding_create_or_update_request(
            resource_group_name=resource_group_name,
            gateway_name=gateway_name,
            hostname_binding_name=hostname_binding_name,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["Azure-AsyncOperation"] = self._deserialize(
            "str", response.headers.get("Azure-AsyncOperation")
        )
        response_headers["location"] = self._deserialize("str", response.headers.get("location"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        gateway_name: str,
        hostname_binding_name: str,
        parameters: _models.GatewayHostnameBindingResource,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.GatewayHostnameBindingResource]:
        """Creates or updates an API Management gateway hostname binding. This is long running operation
        and could take several minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param gateway_name: The name of the API Management gateway. Required.
        :type gateway_name: str
        :param hostname_binding_name: Gateway hostname binding identifier. Must be unique in the scope
         of parent Gateway entity. Required.
        :type hostname_binding_name: str
        :param parameters: Parameters supplied to the CreateOrUpdate API Management gateway hostname
         binding operation. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.GatewayHostnameBindingResource
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns GatewayHostnameBindingResource. The
         GatewayHostnameBindingResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.GatewayHostnameBindingResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        gateway_name: str,
        hostname_binding_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.GatewayHostnameBindingResource]:
        """Creates or updates an API Management gateway hostname binding. This is long running operation
        and could take several minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param gateway_name: The name of the API Management gateway. Required.
        :type gateway_name: str
        :param hostname_binding_name: Gateway hostname binding identifier. Must be unique in the scope
         of parent Gateway entity. Required.
        :type hostname_binding_name: str
        :param parameters: Parameters supplied to the CreateOrUpdate API Management gateway hostname
         binding operation. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns GatewayHostnameBindingResource. The
         GatewayHostnameBindingResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.GatewayHostnameBindingResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        gateway_name: str,
        hostname_binding_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.GatewayHostnameBindingResource]:
        """Creates or updates an API Management gateway hostname binding. This is long running operation
        and could take several minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param gateway_name: The name of the API Management gateway. Required.
        :type gateway_name: str
        :param hostname_binding_name: Gateway hostname binding identifier. Must be unique in the scope
         of parent Gateway entity. Required.
        :type hostname_binding_name: str
        :param parameters: Parameters supplied to the CreateOrUpdate API Management gateway hostname
         binding operation. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns GatewayHostnameBindingResource. The
         GatewayHostnameBindingResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.GatewayHostnameBindingResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        gateway_name: str,
        hostname_binding_name: str,
        parameters: Union[_models.GatewayHostnameBindingResource, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.GatewayHostnameBindingResource]:
        """Creates or updates an API Management gateway hostname binding. This is long running operation
        and could take several minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param gateway_name: The name of the API Management gateway. Required.
        :type gateway_name: str
        :param hostname_binding_name: Gateway hostname binding identifier. Must be unique in the scope
         of parent Gateway entity. Required.
        :type hostname_binding_name: str
        :param parameters: Parameters supplied to the CreateOrUpdate API Management gateway hostname
         binding operation. Is one of the following types: GatewayHostnameBindingResource, JSON,
         IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.GatewayHostnameBindingResource or JSON or
         IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns GatewayHostnameBindingResource. The
         GatewayHostnameBindingResource is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.GatewayHostnameBindingResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.GatewayHostnameBindingResource] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._create_or_update_initial(
                resource_group_name=resource_group_name,
                gateway_name=gateway_name,
                hostname_binding_name=hostname_binding_name,
                parameters=parameters,
                etag=etag,
                match_condition=match_condition,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response_headers = {}
            response = pipeline_response.http_response
            response_headers["Azure-AsyncOperation"] = self._deserialize(
                "str", response.headers.get("Azure-AsyncOperation")
            )
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))

            deserialized = _deserialize(_models.GatewayHostnameBindingResource, response.json())
            if cls:
                return cls(pipeline_response, deserialized, response_headers)  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.GatewayHostnameBindingResource].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.GatewayHostnameBindingResource](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _delete_initial(
        self,
        resource_group_name: str,
        gateway_name: str,
        hostname_binding_name: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        _request = build_api_gateway_hostname_binding_delete_request(
            resource_group_name=resource_group_name,
            gateway_name=gateway_name,
            hostname_binding_name=hostname_binding_name,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [202, 204]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Azure-AsyncOperation"] = self._deserialize(
                "str", response.headers.get("Azure-AsyncOperation")
            )
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def begin_delete(
        self,
        resource_group_name: str,
        gateway_name: str,
        hostname_binding_name: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> AsyncLROPoller[None]:
        """Deletes an existing API Management gateway hostname binding.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param gateway_name: The name of the API Management gateway. Required.
        :type gateway_name: str
        :param hostname_binding_name: Gateway hostname binding identifier. Must be unique in the scope
         of parent Gateway entity. Required.
        :type hostname_binding_name: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns None
        :rtype: ~azure.core.polling.AsyncLROPoller[None]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._delete_initial(
                resource_group_name=resource_group_name,
                gateway_name=gateway_name,
                hostname_binding_name=hostname_binding_name,
                etag=etag,
                match_condition=match_condition,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):  # pylint: disable=inconsistent-return-statements
            if cls:
                return cls(pipeline_response, None, {})  # type: ignore

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[None].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method)  # type: ignore

    @distributed_trace
    def list_by_gateway(
        self, resource_group_name: str, gateway_name: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.GatewayHostnameBindingResource"]:
        """List all API Management gateway hostname bindings within a gateway.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param gateway_name: The name of the API Management gateway. Required.
        :type gateway_name: str
        :return: An iterator like instance of GatewayHostnameBindingResource
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.GatewayHostnameBindingResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.GatewayHostnameBindingResource]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_api_gateway_hostname_binding_list_by_gateway_request(
                    resource_group_name=resource_group_name,
                    gateway_name=gateway_name,
                    subscription_id=self._config.subscription_id,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.GatewayHostnameBindingResource],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    async def _refresh_secret_initial(
        self, resource_group_name: str, gateway_name: str, hostname_binding_name: str, **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        _request = build_api_gateway_hostname_binding_refresh_secret_request(
            resource_group_name=resource_group_name,
            gateway_name=gateway_name,
            hostname_binding_name=hostname_binding_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["Azure-AsyncOperation"] = self._deserialize(
            "str", response.headers.get("Azure-AsyncOperation")
        )
        response_headers["location"] = self._deserialize("str", response.headers.get("location"))
        response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def begin_refresh_secret(
        self, resource_group_name: str, gateway_name: str, hostname_binding_name: str, **kwargs: Any
    ) -> AsyncLROPoller[None]:
        """Refresh the secret for an API Management gateway hostname binding.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param gateway_name: The name of the API Management gateway. Required.
        :type gateway_name: str
        :param hostname_binding_name: Gateway hostname binding identifier. Must be unique in the scope
         of parent Gateway entity. Required.
        :type hostname_binding_name: str
        :return: An instance of AsyncLROPoller that returns None
        :rtype: ~azure.core.polling.AsyncLROPoller[None]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._refresh_secret_initial(
                resource_group_name=resource_group_name,
                gateway_name=gateway_name,
                hostname_binding_name=hostname_binding_name,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):  # pylint: disable=inconsistent-return-statements
            if cls:
                return cls(pipeline_response, None, {})  # type: ignore

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[None].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method)  # type: ignore


class GatewayOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`gateway` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, gateway_id: str, **kwargs: Any
    ) -> _models.GatewayContract:
        """Gets the details of the Gateway specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :return: GatewayContract. The GatewayContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GatewayContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.GatewayContract] = kwargs.pop("cls", None)

        _request = build_gateway_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            gateway_id=gateway_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.GatewayContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(self, resource_group_name: str, service_name: str, gateway_id: str, **kwargs: Any) -> bool:
        """Gets the entity state (Etag) version of the Gateway specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_gateway_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            gateway_id=gateway_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        parameters: _models.GatewayContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.GatewayContract:
        """Creates or updates a Gateway to be used in Api Management instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param parameters: Required.
        :type parameters: ~azure.mgmt.apimanagement.models.GatewayContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: GatewayContract. The GatewayContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GatewayContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.GatewayContract:
        """Creates or updates a Gateway to be used in Api Management instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param parameters: Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: GatewayContract. The GatewayContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GatewayContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.GatewayContract:
        """Creates or updates a Gateway to be used in Api Management instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param parameters: Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: GatewayContract. The GatewayContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GatewayContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        parameters: Union[_models.GatewayContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.GatewayContract:
        """Creates or updates a Gateway to be used in Api Management instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param parameters: Is one of the following types: GatewayContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.GatewayContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: GatewayContract. The GatewayContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GatewayContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.GatewayContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_gateway_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            gateway_id=gateway_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.GatewayContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        parameters: _models.GatewayContract,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.GatewayContract:
        """Updates the details of the gateway specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param parameters: Required.
        :type parameters: ~azure.mgmt.apimanagement.models.GatewayContract
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: GatewayContract. The GatewayContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GatewayContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.GatewayContract:
        """Updates the details of the gateway specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param parameters: Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: GatewayContract. The GatewayContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GatewayContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.GatewayContract:
        """Updates the details of the gateway specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param parameters: Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: GatewayContract. The GatewayContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GatewayContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        parameters: Union[_models.GatewayContract, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.GatewayContract:
        """Updates the details of the gateway specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param parameters: Is one of the following types: GatewayContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.GatewayContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: GatewayContract. The GatewayContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GatewayContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.GatewayContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_gateway_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            gateway_id=gateway_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.GatewayContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes specific Gateway.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_gateway_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            gateway_id=gateway_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.GatewayContract"]:
        """Lists a collection of gateways registered with service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>| region |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         description | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of GatewayContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.GatewayContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.GatewayContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_gateway_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.GatewayContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def list_keys(
        self, resource_group_name: str, service_name: str, gateway_id: str, **kwargs: Any
    ) -> _models.GatewayKeysContract:
        """Retrieves gateway keys.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :return: GatewayKeysContract. The GatewayKeysContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GatewayKeysContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.GatewayKeysContract] = kwargs.pop("cls", None)

        _request = build_gateway_list_keys_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            gateway_id=gateway_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.GatewayKeysContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def regenerate_key(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        parameters: _models.GatewayKeyRegenerationRequestContract,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> None:
        """Regenerates specified gateway key invalidating any tokens created with it.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param parameters: Required.
        :type parameters: ~azure.mgmt.apimanagement.models.GatewayKeyRegenerationRequestContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def regenerate_key(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> None:
        """Regenerates specified gateway key invalidating any tokens created with it.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param parameters: Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def regenerate_key(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> None:
        """Regenerates specified gateway key invalidating any tokens created with it.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param parameters: Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def regenerate_key(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        parameters: Union[_models.GatewayKeyRegenerationRequestContract, JSON, IO[bytes]],
        **kwargs: Any
    ) -> None:
        """Regenerates specified gateway key invalidating any tokens created with it.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param parameters: Is one of the following types: GatewayKeyRegenerationRequestContract, JSON,
         IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.GatewayKeyRegenerationRequestContract or
         JSON or IO[bytes]
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[None] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_gateway_regenerate_key_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            gateway_id=gateway_id,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @overload
    async def generate_token(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        parameters: _models.GatewayTokenRequestContract,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.GatewayTokenContract:
        """Gets the Shared Access Authorization Token for the gateway.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param parameters: Required.
        :type parameters: ~azure.mgmt.apimanagement.models.GatewayTokenRequestContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: GatewayTokenContract. The GatewayTokenContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GatewayTokenContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def generate_token(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.GatewayTokenContract:
        """Gets the Shared Access Authorization Token for the gateway.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param parameters: Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: GatewayTokenContract. The GatewayTokenContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GatewayTokenContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def generate_token(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.GatewayTokenContract:
        """Gets the Shared Access Authorization Token for the gateway.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param parameters: Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: GatewayTokenContract. The GatewayTokenContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GatewayTokenContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def generate_token(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        parameters: Union[_models.GatewayTokenRequestContract, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.GatewayTokenContract:
        """Gets the Shared Access Authorization Token for the gateway.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param parameters: Is one of the following types: GatewayTokenRequestContract, JSON, IO[bytes]
         Required.
        :type parameters: ~azure.mgmt.apimanagement.models.GatewayTokenRequestContract or JSON or
         IO[bytes]
        :return: GatewayTokenContract. The GatewayTokenContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GatewayTokenContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.GatewayTokenContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_gateway_generate_token_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            gateway_id=gateway_id,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.GatewayTokenContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def invalidate_debug_credentials(
        self, resource_group_name: str, service_name: str, gateway_id: str, **kwargs: Any
    ) -> None:
        """Action is invalidating all debug credentials issued for gateway.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_gateway_invalidate_debug_credentials_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            gateway_id=gateway_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @overload
    async def list_debug_credentials(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        parameters: _models.GatewayListDebugCredentialsContract,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.GatewayDebugCredentialsContract:
        """Create new debug credentials for gateway.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param parameters: List debug credentials properties. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.GatewayListDebugCredentialsContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: GatewayDebugCredentialsContract. The GatewayDebugCredentialsContract is compatible
         with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GatewayDebugCredentialsContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def list_debug_credentials(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.GatewayDebugCredentialsContract:
        """Create new debug credentials for gateway.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param parameters: List debug credentials properties. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: GatewayDebugCredentialsContract. The GatewayDebugCredentialsContract is compatible
         with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GatewayDebugCredentialsContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def list_debug_credentials(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.GatewayDebugCredentialsContract:
        """Create new debug credentials for gateway.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param parameters: List debug credentials properties. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: GatewayDebugCredentialsContract. The GatewayDebugCredentialsContract is compatible
         with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GatewayDebugCredentialsContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def list_debug_credentials(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        parameters: Union[_models.GatewayListDebugCredentialsContract, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.GatewayDebugCredentialsContract:
        """Create new debug credentials for gateway.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param parameters: List debug credentials properties. Is one of the following types:
         GatewayListDebugCredentialsContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.GatewayListDebugCredentialsContract or JSON
         or IO[bytes]
        :return: GatewayDebugCredentialsContract. The GatewayDebugCredentialsContract is compatible
         with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GatewayDebugCredentialsContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.GatewayDebugCredentialsContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_gateway_list_debug_credentials_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            gateway_id=gateway_id,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.GatewayDebugCredentialsContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def list_trace(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        parameters: _models.GatewayListTraceContract,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> dict[str, Any]:
        """Fetches trace collected by gateway.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param parameters: List trace properties. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.GatewayListTraceContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: dict mapping str to any
        :rtype: dict[str, any]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def list_trace(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> dict[str, Any]:
        """Fetches trace collected by gateway.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param parameters: List trace properties. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: dict mapping str to any
        :rtype: dict[str, any]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def list_trace(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> dict[str, Any]:
        """Fetches trace collected by gateway.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param parameters: List trace properties. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: dict mapping str to any
        :rtype: dict[str, any]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def list_trace(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        parameters: Union[_models.GatewayListTraceContract, JSON, IO[bytes]],
        **kwargs: Any
    ) -> dict[str, Any]:
        """Fetches trace collected by gateway.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param parameters: List trace properties. Is one of the following types:
         GatewayListTraceContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.GatewayListTraceContract or JSON or
         IO[bytes]
        :return: dict mapping str to any
        :rtype: dict[str, any]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[dict[str, Any]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_gateway_list_trace_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            gateway_id=gateway_id,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(dict[str, Any], response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class GatewayApiOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`gateway_api` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.ApiContract"]:
        """Lists a collection of the APIs associated with a gateway.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of ApiContract
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ApiContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ApiContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_gateway_api_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    gateway_id=gateway_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ApiContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, gateway_id: str, api_id: str, **kwargs: Any
    ) -> bool:
        """Checks that API entity specified by identifier is associated with the Gateway entity.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_gateway_api_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            gateway_id=gateway_id,
            api_id=api_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        api_id: str,
        parameters: Optional[_models.AssociationContract] = None,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ApiContract:
        """Adds an API to the specified Gateway.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param parameters: Default value is None.
        :type parameters: ~azure.mgmt.apimanagement.models.AssociationContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ApiContract. The ApiContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        api_id: str,
        parameters: Optional[JSON] = None,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ApiContract:
        """Adds an API to the specified Gateway.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param parameters: Default value is None.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ApiContract. The ApiContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        api_id: str,
        parameters: Optional[IO[bytes]] = None,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ApiContract:
        """Adds an API to the specified Gateway.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param parameters: Default value is None.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ApiContract. The ApiContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        api_id: str,
        parameters: Optional[Union[_models.AssociationContract, JSON, IO[bytes]]] = None,
        **kwargs: Any
    ) -> _models.ApiContract:
        """Adds an API to the specified Gateway.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :param parameters: Is one of the following types: AssociationContract, JSON, IO[bytes] Default
         value is None.
        :type parameters: ~azure.mgmt.apimanagement.models.AssociationContract or JSON or IO[bytes]
        :return: ApiContract. The ApiContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        content_type = content_type if parameters else None
        cls: ClsType[_models.ApiContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json" if parameters else None
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            if parameters is not None:
                _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore
            else:
                _content = None

        _request = build_gateway_api_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            gateway_id=gateway_id,
            api_id=api_id,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ApiContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self, resource_group_name: str, service_name: str, gateway_id: str, api_id: str, **kwargs: Any
    ) -> None:
        """Deletes the specified API from the specified Gateway.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param api_id: API identifier. Must be unique in the current API Management service instance.
         Required.
        :type api_id: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_gateway_api_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            gateway_id=gateway_id,
            api_id=api_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore


class GatewayHostnameConfigurationOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`gateway_hostname_configuration` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, gateway_id: str, hc_id: str, **kwargs: Any
    ) -> _models.GatewayHostnameConfigurationContract:
        """Get details of a hostname configuration.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param hc_id: Gateway hostname configuration identifier. Must be unique in the scope of parent
         Gateway entity. Required.
        :type hc_id: str
        :return: GatewayHostnameConfigurationContract. The GatewayHostnameConfigurationContract is
         compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GatewayHostnameConfigurationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.GatewayHostnameConfigurationContract] = kwargs.pop("cls", None)

        _request = build_gateway_hostname_configuration_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            gateway_id=gateway_id,
            hc_id=hc_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.GatewayHostnameConfigurationContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, gateway_id: str, hc_id: str, **kwargs: Any
    ) -> bool:
        """Checks that hostname configuration entity specified by identifier exists for specified Gateway
        entity.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param hc_id: Gateway hostname configuration identifier. Must be unique in the scope of parent
         Gateway entity. Required.
        :type hc_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_gateway_hostname_configuration_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            gateway_id=gateway_id,
            hc_id=hc_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        hc_id: str,
        parameters: _models.GatewayHostnameConfigurationContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.GatewayHostnameConfigurationContract:
        """Creates of updates hostname configuration for a Gateway.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param hc_id: Gateway hostname configuration identifier. Must be unique in the scope of parent
         Gateway entity. Required.
        :type hc_id: str
        :param parameters: Required.
        :type parameters: ~azure.mgmt.apimanagement.models.GatewayHostnameConfigurationContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: GatewayHostnameConfigurationContract. The GatewayHostnameConfigurationContract is
         compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GatewayHostnameConfigurationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        hc_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.GatewayHostnameConfigurationContract:
        """Creates of updates hostname configuration for a Gateway.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param hc_id: Gateway hostname configuration identifier. Must be unique in the scope of parent
         Gateway entity. Required.
        :type hc_id: str
        :param parameters: Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: GatewayHostnameConfigurationContract. The GatewayHostnameConfigurationContract is
         compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GatewayHostnameConfigurationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        hc_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.GatewayHostnameConfigurationContract:
        """Creates of updates hostname configuration for a Gateway.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param hc_id: Gateway hostname configuration identifier. Must be unique in the scope of parent
         Gateway entity. Required.
        :type hc_id: str
        :param parameters: Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: GatewayHostnameConfigurationContract. The GatewayHostnameConfigurationContract is
         compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GatewayHostnameConfigurationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        hc_id: str,
        parameters: Union[_models.GatewayHostnameConfigurationContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.GatewayHostnameConfigurationContract:
        """Creates of updates hostname configuration for a Gateway.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param hc_id: Gateway hostname configuration identifier. Must be unique in the scope of parent
         Gateway entity. Required.
        :type hc_id: str
        :param parameters: Is one of the following types: GatewayHostnameConfigurationContract, JSON,
         IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.GatewayHostnameConfigurationContract or JSON
         or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: GatewayHostnameConfigurationContract. The GatewayHostnameConfigurationContract is
         compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GatewayHostnameConfigurationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.GatewayHostnameConfigurationContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_gateway_hostname_configuration_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            gateway_id=gateway_id,
            hc_id=hc_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 200:
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if response.status_code == 201:
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.GatewayHostnameConfigurationContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        hc_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes the specified hostname configuration from the specified Gateway.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param hc_id: Gateway hostname configuration identifier. Must be unique in the scope of parent
         Gateway entity. Required.
        :type hc_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_gateway_hostname_configuration_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            gateway_id=gateway_id,
            hc_id=hc_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.GatewayHostnameConfigurationContract"]:
        """Lists the collection of hostname configurations for the specified gateway.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>| hostname
         | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of GatewayHostnameConfigurationContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.GatewayHostnameConfigurationContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.GatewayHostnameConfigurationContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_gateway_hostname_configuration_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    gateway_id=gateway_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.GatewayHostnameConfigurationContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class GatewayCertificateAuthorityOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`gateway_certificate_authority` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, gateway_id: str, certificate_id: str, **kwargs: Any
    ) -> _models.GatewayCertificateAuthorityContract:
        """Get assigned Gateway Certificate Authority details.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param certificate_id: Identifier of the certificate entity. Must be unique in the current API
         Management service instance. Required.
        :type certificate_id: str
        :return: GatewayCertificateAuthorityContract. The GatewayCertificateAuthorityContract is
         compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GatewayCertificateAuthorityContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.GatewayCertificateAuthorityContract] = kwargs.pop("cls", None)

        _request = build_gateway_certificate_authority_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            gateway_id=gateway_id,
            certificate_id=certificate_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.GatewayCertificateAuthorityContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, gateway_id: str, certificate_id: str, **kwargs: Any
    ) -> bool:
        """Checks if Certificate entity is assigned to Gateway entity as Certificate Authority.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param certificate_id: Identifier of the certificate entity. Must be unique in the current API
         Management service instance. Required.
        :type certificate_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_gateway_certificate_authority_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            gateway_id=gateway_id,
            certificate_id=certificate_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        certificate_id: str,
        parameters: _models.GatewayCertificateAuthorityContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.GatewayCertificateAuthorityContract:
        """Assign Certificate entity to Gateway entity as Certificate Authority.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param certificate_id: Identifier of the certificate entity. Must be unique in the current API
         Management service instance. Required.
        :type certificate_id: str
        :param parameters: Required.
        :type parameters: ~azure.mgmt.apimanagement.models.GatewayCertificateAuthorityContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: GatewayCertificateAuthorityContract. The GatewayCertificateAuthorityContract is
         compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GatewayCertificateAuthorityContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        certificate_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.GatewayCertificateAuthorityContract:
        """Assign Certificate entity to Gateway entity as Certificate Authority.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param certificate_id: Identifier of the certificate entity. Must be unique in the current API
         Management service instance. Required.
        :type certificate_id: str
        :param parameters: Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: GatewayCertificateAuthorityContract. The GatewayCertificateAuthorityContract is
         compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GatewayCertificateAuthorityContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        certificate_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.GatewayCertificateAuthorityContract:
        """Assign Certificate entity to Gateway entity as Certificate Authority.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param certificate_id: Identifier of the certificate entity. Must be unique in the current API
         Management service instance. Required.
        :type certificate_id: str
        :param parameters: Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: GatewayCertificateAuthorityContract. The GatewayCertificateAuthorityContract is
         compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GatewayCertificateAuthorityContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        certificate_id: str,
        parameters: Union[_models.GatewayCertificateAuthorityContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.GatewayCertificateAuthorityContract:
        """Assign Certificate entity to Gateway entity as Certificate Authority.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param certificate_id: Identifier of the certificate entity. Must be unique in the current API
         Management service instance. Required.
        :type certificate_id: str
        :param parameters: Is one of the following types: GatewayCertificateAuthorityContract, JSON,
         IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.GatewayCertificateAuthorityContract or JSON
         or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: GatewayCertificateAuthorityContract. The GatewayCertificateAuthorityContract is
         compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GatewayCertificateAuthorityContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.GatewayCertificateAuthorityContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_gateway_certificate_authority_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            gateway_id=gateway_id,
            certificate_id=certificate_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.GatewayCertificateAuthorityContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        certificate_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Remove relationship between Certificate Authority and Gateway entity.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :param certificate_id: Identifier of the certificate entity. Must be unique in the current API
         Management service instance. Required.
        :type certificate_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_gateway_certificate_authority_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            gateway_id=gateway_id,
            certificate_id=certificate_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        gateway_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.GatewayCertificateAuthorityContract"]:
        """Lists the collection of Certificate Authorities for the specified Gateway entity.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param gateway_id: Gateway entity identifier. Must be unique in the current API Management
         service instance. Must not have value 'managed'. Required.
        :type gateway_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | eq, ne |  |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of GatewayCertificateAuthorityContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.GatewayCertificateAuthorityContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.GatewayCertificateAuthorityContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_gateway_certificate_authority_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    gateway_id=gateway_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.GatewayCertificateAuthorityContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class GroupOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`group` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, group_id: str, **kwargs: Any
    ) -> _models.GroupContract:
        """Gets the details of the group specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param group_id: Group identifier. Must be unique in the current API Management service
         instance. Required.
        :type group_id: str
        :return: GroupContract. The GroupContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GroupContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.GroupContract] = kwargs.pop("cls", None)

        _request = build_group_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            group_id=group_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.GroupContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(self, resource_group_name: str, service_name: str, group_id: str, **kwargs: Any) -> bool:
        """Gets the entity state (Etag) version of the group specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param group_id: Group identifier. Must be unique in the current API Management service
         instance. Required.
        :type group_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_group_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            group_id=group_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        group_id: str,
        parameters: _models.GroupCreateParameters,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.GroupContract:
        """Creates or Updates a group.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param group_id: Group identifier. Must be unique in the current API Management service
         instance. Required.
        :type group_id: str
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.GroupCreateParameters
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: GroupContract. The GroupContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GroupContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        group_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.GroupContract:
        """Creates or Updates a group.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param group_id: Group identifier. Must be unique in the current API Management service
         instance. Required.
        :type group_id: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: GroupContract. The GroupContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GroupContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        group_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.GroupContract:
        """Creates or Updates a group.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param group_id: Group identifier. Must be unique in the current API Management service
         instance. Required.
        :type group_id: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: GroupContract. The GroupContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GroupContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        group_id: str,
        parameters: Union[_models.GroupCreateParameters, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.GroupContract:
        """Creates or Updates a group.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param group_id: Group identifier. Must be unique in the current API Management service
         instance. Required.
        :type group_id: str
        :param parameters: Create parameters. Is one of the following types: GroupCreateParameters,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.GroupCreateParameters or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: GroupContract. The GroupContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GroupContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.GroupContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_group_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            group_id=group_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 200:
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if response.status_code == 201:
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.GroupContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        group_id: str,
        parameters: _models.GroupUpdateParameters,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.GroupContract:
        """Updates the details of the group specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param group_id: Group identifier. Must be unique in the current API Management service
         instance. Required.
        :type group_id: str
        :param parameters: Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.GroupUpdateParameters
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: GroupContract. The GroupContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GroupContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        group_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.GroupContract:
        """Updates the details of the group specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param group_id: Group identifier. Must be unique in the current API Management service
         instance. Required.
        :type group_id: str
        :param parameters: Update parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: GroupContract. The GroupContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GroupContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        group_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.GroupContract:
        """Updates the details of the group specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param group_id: Group identifier. Must be unique in the current API Management service
         instance. Required.
        :type group_id: str
        :param parameters: Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: GroupContract. The GroupContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GroupContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        group_id: str,
        parameters: Union[_models.GroupUpdateParameters, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.GroupContract:
        """Updates the details of the group specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param group_id: Group identifier. Must be unique in the current API Management service
         instance. Required.
        :type group_id: str
        :param parameters: Update parameters. Is one of the following types: GroupUpdateParameters,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.GroupUpdateParameters or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: GroupContract. The GroupContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GroupContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.GroupContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_group_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            group_id=group_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.GroupContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        group_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes specific group of the API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param group_id: Group identifier. Must be unique in the current API Management service
         instance. Required.
        :type group_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_group_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            group_id=group_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.GroupContract"]:
        """Lists a collection of groups defined within a service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         displayName | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>| description | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
         endswith |</br>| externalId | filter | eq |     |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of GroupContract
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.GroupContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.GroupContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_group_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.GroupContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class GroupUserOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`group_user` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list(
        self,
        resource_group_name: str,
        service_name: str,
        group_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.UserContract"]:
        """Lists a collection of user entities associated with the group.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param group_id: Group identifier. Must be unique in the current API Management service
         instance. Required.
        :type group_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>| firstName
         | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         lastName | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>| email | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>| registrationDate | filter | ge, le, eq, ne, gt, lt |     |</br>| note | filter | ge,
         le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of UserContract
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.UserContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.UserContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_group_user_list_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    group_id=group_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.UserContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def check_entity_exists(
        self, resource_group_name: str, service_name: str, group_id: str, user_id: str, **kwargs: Any
    ) -> bool:
        """Checks that user entity specified by identifier is associated with the group entity.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param group_id: Group identifier. Must be unique in the current API Management service
         instance. Required.
        :type group_id: str
        :param user_id: User identifier. Must be unique in the current API Management service instance.
         Required.
        :type user_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_group_user_check_entity_exists_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            group_id=group_id,
            user_id=user_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [204, 404]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore
        return 200 <= response.status_code <= 299

    @distributed_trace_async
    async def create(
        self, resource_group_name: str, service_name: str, group_id: str, user_id: str, **kwargs: Any
    ) -> _models.UserContract:
        """Add existing user to existing group.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param group_id: Group identifier. Must be unique in the current API Management service
         instance. Required.
        :type group_id: str
        :param user_id: User identifier. Must be unique in the current API Management service instance.
         Required.
        :type user_id: str
        :return: UserContract. The UserContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.UserContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.UserContract] = kwargs.pop("cls", None)

        _request = build_group_user_create_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            group_id=group_id,
            user_id=user_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.UserContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self, resource_group_name: str, service_name: str, group_id: str, user_id: str, **kwargs: Any
    ) -> None:
        """Remove existing user from existing group.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param group_id: Group identifier. Must be unique in the current API Management service
         instance. Required.
        :type group_id: str
        :param user_id: User identifier. Must be unique in the current API Management service instance.
         Required.
        :type user_id: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_group_user_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            group_id=group_id,
            user_id=user_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore


class WorkspaceGroupUserOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`workspace_group_user` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        group_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.UserContract"]:
        """Lists a collection of user entities associated with the group.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param group_id: Group identifier. Must be unique in the current API Management service
         instance. Required.
        :type group_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>| firstName
         | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         lastName | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>| email | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>| registrationDate | filter | ge, le, eq, ne, gt, lt |     |</br>| note | filter | ge,
         le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of UserContract
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.UserContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.UserContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_workspace_group_user_list_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    workspace_id=workspace_id,
                    group_id=group_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.UserContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def check_entity_exists(
        self, resource_group_name: str, service_name: str, workspace_id: str, group_id: str, user_id: str, **kwargs: Any
    ) -> bool:
        """Checks that user entity specified by identifier is associated with the group entity.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param group_id: Group identifier. Must be unique in the current API Management service
         instance. Required.
        :type group_id: str
        :param user_id: User identifier. Must be unique in the current API Management service instance.
         Required.
        :type user_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_group_user_check_entity_exists_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            group_id=group_id,
            user_id=user_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [204, 404]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore
        return 200 <= response.status_code <= 299

    @distributed_trace_async
    async def create(
        self, resource_group_name: str, service_name: str, workspace_id: str, group_id: str, user_id: str, **kwargs: Any
    ) -> _models.UserContract:
        """Add existing user to existing group.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param group_id: Group identifier. Must be unique in the current API Management service
         instance. Required.
        :type group_id: str
        :param user_id: User identifier. Must be unique in the current API Management service instance.
         Required.
        :type user_id: str
        :return: UserContract. The UserContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.UserContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.UserContract] = kwargs.pop("cls", None)

        _request = build_workspace_group_user_create_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            group_id=group_id,
            user_id=user_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.UserContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self, resource_group_name: str, service_name: str, workspace_id: str, group_id: str, user_id: str, **kwargs: Any
    ) -> None:
        """Remove existing user from existing group.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param group_id: Group identifier. Must be unique in the current API Management service
         instance. Required.
        :type group_id: str
        :param user_id: User identifier. Must be unique in the current API Management service instance.
         Required.
        :type user_id: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_group_user_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            group_id=group_id,
            user_id=user_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore


class IdentityProviderOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`identity_provider` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self,
        resource_group_name: str,
        service_name: str,
        identity_provider_name: Union[str, _models.IdentityProviderType],
        **kwargs: Any
    ) -> _models.IdentityProviderContract:
        """Gets the configuration details of the identity Provider configured in specified service
        instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param identity_provider_name: Identity Provider Type identifier. Known values are: "facebook",
         "google", "microsoft", "twitter", "aad", and "aadB2C". Required.
        :type identity_provider_name: str or ~azure.mgmt.apimanagement.models.IdentityProviderType
        :return: IdentityProviderContract. The IdentityProviderContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.IdentityProviderContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.IdentityProviderContract] = kwargs.pop("cls", None)

        _request = build_identity_provider_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            identity_provider_name=identity_provider_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.IdentityProviderContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self,
        resource_group_name: str,
        service_name: str,
        identity_provider_name: Union[str, _models.IdentityProviderType],
        **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the identityProvider specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param identity_provider_name: Identity Provider Type identifier. Known values are: "facebook",
         "google", "microsoft", "twitter", "aad", and "aadB2C". Required.
        :type identity_provider_name: str or ~azure.mgmt.apimanagement.models.IdentityProviderType
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_identity_provider_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            identity_provider_name=identity_provider_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        identity_provider_name: Union[str, _models.IdentityProviderType],
        parameters: _models.IdentityProviderCreateContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.IdentityProviderContract:
        """Creates or Updates the IdentityProvider configuration.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param identity_provider_name: Identity Provider Type identifier. Known values are: "facebook",
         "google", "microsoft", "twitter", "aad", and "aadB2C". Required.
        :type identity_provider_name: str or ~azure.mgmt.apimanagement.models.IdentityProviderType
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.IdentityProviderCreateContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: IdentityProviderContract. The IdentityProviderContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.IdentityProviderContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        identity_provider_name: Union[str, _models.IdentityProviderType],
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.IdentityProviderContract:
        """Creates or Updates the IdentityProvider configuration.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param identity_provider_name: Identity Provider Type identifier. Known values are: "facebook",
         "google", "microsoft", "twitter", "aad", and "aadB2C". Required.
        :type identity_provider_name: str or ~azure.mgmt.apimanagement.models.IdentityProviderType
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: IdentityProviderContract. The IdentityProviderContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.IdentityProviderContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        identity_provider_name: Union[str, _models.IdentityProviderType],
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.IdentityProviderContract:
        """Creates or Updates the IdentityProvider configuration.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param identity_provider_name: Identity Provider Type identifier. Known values are: "facebook",
         "google", "microsoft", "twitter", "aad", and "aadB2C". Required.
        :type identity_provider_name: str or ~azure.mgmt.apimanagement.models.IdentityProviderType
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: IdentityProviderContract. The IdentityProviderContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.IdentityProviderContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        identity_provider_name: Union[str, _models.IdentityProviderType],
        parameters: Union[_models.IdentityProviderCreateContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.IdentityProviderContract:
        """Creates or Updates the IdentityProvider configuration.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param identity_provider_name: Identity Provider Type identifier. Known values are: "facebook",
         "google", "microsoft", "twitter", "aad", and "aadB2C". Required.
        :type identity_provider_name: str or ~azure.mgmt.apimanagement.models.IdentityProviderType
        :param parameters: Create parameters. Is one of the following types:
         IdentityProviderCreateContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.IdentityProviderCreateContract or JSON or
         IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: IdentityProviderContract. The IdentityProviderContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.IdentityProviderContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.IdentityProviderContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_identity_provider_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            identity_provider_name=identity_provider_name,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.IdentityProviderContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        identity_provider_name: Union[str, _models.IdentityProviderType],
        parameters: _models.IdentityProviderUpdateParameters,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.IdentityProviderContract:
        """Updates an existing IdentityProvider configuration.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param identity_provider_name: Identity Provider Type identifier. Known values are: "facebook",
         "google", "microsoft", "twitter", "aad", and "aadB2C". Required.
        :type identity_provider_name: str or ~azure.mgmt.apimanagement.models.IdentityProviderType
        :param parameters: Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.IdentityProviderUpdateParameters
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: IdentityProviderContract. The IdentityProviderContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.IdentityProviderContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        identity_provider_name: Union[str, _models.IdentityProviderType],
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.IdentityProviderContract:
        """Updates an existing IdentityProvider configuration.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param identity_provider_name: Identity Provider Type identifier. Known values are: "facebook",
         "google", "microsoft", "twitter", "aad", and "aadB2C". Required.
        :type identity_provider_name: str or ~azure.mgmt.apimanagement.models.IdentityProviderType
        :param parameters: Update parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: IdentityProviderContract. The IdentityProviderContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.IdentityProviderContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        identity_provider_name: Union[str, _models.IdentityProviderType],
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.IdentityProviderContract:
        """Updates an existing IdentityProvider configuration.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param identity_provider_name: Identity Provider Type identifier. Known values are: "facebook",
         "google", "microsoft", "twitter", "aad", and "aadB2C". Required.
        :type identity_provider_name: str or ~azure.mgmt.apimanagement.models.IdentityProviderType
        :param parameters: Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: IdentityProviderContract. The IdentityProviderContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.IdentityProviderContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        identity_provider_name: Union[str, _models.IdentityProviderType],
        parameters: Union[_models.IdentityProviderUpdateParameters, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.IdentityProviderContract:
        """Updates an existing IdentityProvider configuration.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param identity_provider_name: Identity Provider Type identifier. Known values are: "facebook",
         "google", "microsoft", "twitter", "aad", and "aadB2C". Required.
        :type identity_provider_name: str or ~azure.mgmt.apimanagement.models.IdentityProviderType
        :param parameters: Update parameters. Is one of the following types:
         IdentityProviderUpdateParameters, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.IdentityProviderUpdateParameters or JSON or
         IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: IdentityProviderContract. The IdentityProviderContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.IdentityProviderContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.IdentityProviderContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_identity_provider_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            identity_provider_name=identity_provider_name,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.IdentityProviderContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        identity_provider_name: Union[str, _models.IdentityProviderType],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes the specified identity provider configuration.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param identity_provider_name: Identity Provider Type identifier. Known values are: "facebook",
         "google", "microsoft", "twitter", "aad", and "aadB2C". Required.
        :type identity_provider_name: str or ~azure.mgmt.apimanagement.models.IdentityProviderType
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_identity_provider_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            identity_provider_name=identity_provider_name,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self, resource_group_name: str, service_name: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.IdentityProviderContract"]:
        """Lists a collection of Identity Provider configured in the specified service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :return: An iterator like instance of IdentityProviderContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.IdentityProviderContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.IdentityProviderContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_identity_provider_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.IdentityProviderContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def list_secrets(
        self,
        resource_group_name: str,
        service_name: str,
        identity_provider_name: Union[str, _models.IdentityProviderType],
        **kwargs: Any
    ) -> _models.ClientSecretContract:
        """Gets the client secret details of the Identity Provider.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param identity_provider_name: Identity Provider Type identifier. Known values are: "facebook",
         "google", "microsoft", "twitter", "aad", and "aadB2C". Required.
        :type identity_provider_name: str or ~azure.mgmt.apimanagement.models.IdentityProviderType
        :return: ClientSecretContract. The ClientSecretContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ClientSecretContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ClientSecretContract] = kwargs.pop("cls", None)

        _request = build_identity_provider_list_secrets_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            identity_provider_name=identity_provider_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ClientSecretContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore


class LoggerOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`logger` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, logger_id: str, **kwargs: Any
    ) -> _models.LoggerContract:
        """Gets the details of the logger specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param logger_id: Logger identifier. Must be unique in the API Management service instance.
         Required.
        :type logger_id: str
        :return: LoggerContract. The LoggerContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.LoggerContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.LoggerContract] = kwargs.pop("cls", None)

        _request = build_logger_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            logger_id=logger_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.LoggerContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(self, resource_group_name: str, service_name: str, logger_id: str, **kwargs: Any) -> bool:
        """Gets the entity state (Etag) version of the logger specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param logger_id: Logger identifier. Must be unique in the API Management service instance.
         Required.
        :type logger_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_logger_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            logger_id=logger_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        logger_id: str,
        parameters: _models.LoggerContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.LoggerContract:
        """Creates or Updates a logger.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param logger_id: Logger identifier. Must be unique in the API Management service instance.
         Required.
        :type logger_id: str
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.LoggerContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: LoggerContract. The LoggerContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.LoggerContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        logger_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.LoggerContract:
        """Creates or Updates a logger.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param logger_id: Logger identifier. Must be unique in the API Management service instance.
         Required.
        :type logger_id: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: LoggerContract. The LoggerContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.LoggerContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        logger_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.LoggerContract:
        """Creates or Updates a logger.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param logger_id: Logger identifier. Must be unique in the API Management service instance.
         Required.
        :type logger_id: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: LoggerContract. The LoggerContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.LoggerContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        logger_id: str,
        parameters: Union[_models.LoggerContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.LoggerContract:
        """Creates or Updates a logger.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param logger_id: Logger identifier. Must be unique in the API Management service instance.
         Required.
        :type logger_id: str
        :param parameters: Create parameters. Is one of the following types: LoggerContract, JSON,
         IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.LoggerContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: LoggerContract. The LoggerContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.LoggerContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.LoggerContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_logger_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            logger_id=logger_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.LoggerContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        logger_id: str,
        parameters: _models.LoggerUpdateContract,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.LoggerContract:
        """Updates an existing logger.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param logger_id: Logger identifier. Must be unique in the API Management service instance.
         Required.
        :type logger_id: str
        :param parameters: Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.LoggerUpdateContract
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: LoggerContract. The LoggerContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.LoggerContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        logger_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.LoggerContract:
        """Updates an existing logger.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param logger_id: Logger identifier. Must be unique in the API Management service instance.
         Required.
        :type logger_id: str
        :param parameters: Update parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: LoggerContract. The LoggerContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.LoggerContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        logger_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.LoggerContract:
        """Updates an existing logger.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param logger_id: Logger identifier. Must be unique in the API Management service instance.
         Required.
        :type logger_id: str
        :param parameters: Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: LoggerContract. The LoggerContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.LoggerContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        logger_id: str,
        parameters: Union[_models.LoggerUpdateContract, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.LoggerContract:
        """Updates an existing logger.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param logger_id: Logger identifier. Must be unique in the API Management service instance.
         Required.
        :type logger_id: str
        :param parameters: Update parameters. Is one of the following types: LoggerUpdateContract,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.LoggerUpdateContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: LoggerContract. The LoggerContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.LoggerContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.LoggerContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_logger_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            logger_id=logger_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.LoggerContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        logger_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes the specified logger.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param logger_id: Logger identifier. Must be unique in the API Management service instance.
         Required.
        :type logger_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_logger_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            logger_id=logger_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.LoggerContract"]:
        """Lists a collection of loggers in the specified service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         description | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>| loggerType | filter | eq |     |</br>| resourceId | filter | ge, le, eq, ne, gt, lt |
         substringof, contains, startswith, endswith |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of LoggerContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.LoggerContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.LoggerContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_logger_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.LoggerContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class NamedValueOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`named_value` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, named_value_id: str, **kwargs: Any
    ) -> _models.NamedValueContract:
        """Gets the details of the named value specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param named_value_id: Identifier of the NamedValue. Required.
        :type named_value_id: str
        :return: NamedValueContract. The NamedValueContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.NamedValueContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.NamedValueContract] = kwargs.pop("cls", None)

        _request = build_named_value_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            named_value_id=named_value_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.NamedValueContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, named_value_id: str, **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the named value specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param named_value_id: Identifier of the NamedValue. Required.
        :type named_value_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_named_value_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            named_value_id=named_value_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    async def _create_or_update_initial(
        self,
        resource_group_name: str,
        service_name: str,
        named_value_id: str,
        parameters: Union[_models.NamedValueCreateContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_named_value_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            named_value_id=named_value_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["Azure-AsyncOperation"] = self._deserialize(
            "str", response.headers.get("Azure-AsyncOperation")
        )
        response_headers["location"] = self._deserialize("str", response.headers.get("location"))
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        named_value_id: str,
        parameters: _models.NamedValueCreateContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.NamedValueContract]:
        """Creates or updates named value.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param named_value_id: Identifier of the NamedValue. Required.
        :type named_value_id: str
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.NamedValueCreateContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns NamedValueContract. The NamedValueContract
         is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.NamedValueContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        named_value_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.NamedValueContract]:
        """Creates or updates named value.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param named_value_id: Identifier of the NamedValue. Required.
        :type named_value_id: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns NamedValueContract. The NamedValueContract
         is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.NamedValueContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        named_value_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.NamedValueContract]:
        """Creates or updates named value.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param named_value_id: Identifier of the NamedValue. Required.
        :type named_value_id: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns NamedValueContract. The NamedValueContract
         is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.NamedValueContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        named_value_id: str,
        parameters: Union[_models.NamedValueCreateContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.NamedValueContract]:
        """Creates or updates named value.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param named_value_id: Identifier of the NamedValue. Required.
        :type named_value_id: str
        :param parameters: Create parameters. Is one of the following types: NamedValueCreateContract,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.NamedValueCreateContract or JSON or
         IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns NamedValueContract. The NamedValueContract
         is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.NamedValueContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.NamedValueContract] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._create_or_update_initial(
                resource_group_name=resource_group_name,
                service_name=service_name,
                named_value_id=named_value_id,
                parameters=parameters,
                etag=etag,
                match_condition=match_condition,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response_headers = {}
            response = pipeline_response.http_response
            response_headers["Azure-AsyncOperation"] = self._deserialize(
                "str", response.headers.get("Azure-AsyncOperation")
            )
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

            deserialized = _deserialize(_models.NamedValueContract, response.json())
            if cls:
                return cls(pipeline_response, deserialized, response_headers)  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.NamedValueContract].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.NamedValueContract](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _update_initial(
        self,
        resource_group_name: str,
        service_name: str,
        named_value_id: str,
        parameters: Union[_models.NamedValueUpdateParameters, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_named_value_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            named_value_id=named_value_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 200:
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if response.status_code == 202:
            response_headers["Azure-AsyncOperation"] = self._deserialize(
                "str", response.headers.get("Azure-AsyncOperation")
            )
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_update(
        self,
        resource_group_name: str,
        service_name: str,
        named_value_id: str,
        parameters: _models.NamedValueUpdateParameters,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.NamedValueContract]:
        """Updates the specific named value.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param named_value_id: Identifier of the NamedValue. Required.
        :type named_value_id: str
        :param parameters: Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.NamedValueUpdateParameters
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns NamedValueContract. The NamedValueContract
         is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.NamedValueContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_update(
        self,
        resource_group_name: str,
        service_name: str,
        named_value_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.NamedValueContract]:
        """Updates the specific named value.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param named_value_id: Identifier of the NamedValue. Required.
        :type named_value_id: str
        :param parameters: Update parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns NamedValueContract. The NamedValueContract
         is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.NamedValueContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_update(
        self,
        resource_group_name: str,
        service_name: str,
        named_value_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.NamedValueContract]:
        """Updates the specific named value.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param named_value_id: Identifier of the NamedValue. Required.
        :type named_value_id: str
        :param parameters: Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns NamedValueContract. The NamedValueContract
         is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.NamedValueContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_update(
        self,
        resource_group_name: str,
        service_name: str,
        named_value_id: str,
        parameters: Union[_models.NamedValueUpdateParameters, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.NamedValueContract]:
        """Updates the specific named value.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param named_value_id: Identifier of the NamedValue. Required.
        :type named_value_id: str
        :param parameters: Update parameters. Is one of the following types:
         NamedValueUpdateParameters, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.NamedValueUpdateParameters or JSON or
         IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns NamedValueContract. The NamedValueContract
         is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.NamedValueContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.NamedValueContract] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._update_initial(
                resource_group_name=resource_group_name,
                service_name=service_name,
                named_value_id=named_value_id,
                parameters=parameters,
                etag=etag,
                match_condition=match_condition,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response_headers = {}
            response = pipeline_response.http_response
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

            deserialized = _deserialize(_models.NamedValueContract, response.json())
            if cls:
                return cls(pipeline_response, deserialized, response_headers)  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.NamedValueContract].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.NamedValueContract](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        named_value_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes specific named value from the API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param named_value_id: Identifier of the NamedValue. Required.
        :type named_value_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_named_value_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            named_value_id=named_value_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        is_key_vault_refresh_failed: Optional[bool] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.NamedValueContract"]:
        """Lists a collection of named values defined within a service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| tags |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith, any, all |</br>|
         displayName | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :keyword is_key_vault_refresh_failed: When set to true, the response contains only named value
         entities which failed refresh. Default value is None.
        :paramtype is_key_vault_refresh_failed: bool
        :return: An iterator like instance of NamedValueContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.NamedValueContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.NamedValueContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_named_value_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    is_key_vault_refresh_failed=is_key_vault_refresh_failed,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.NamedValueContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def list_value(
        self, resource_group_name: str, service_name: str, named_value_id: str, **kwargs: Any
    ) -> _models.NamedValueSecretContract:
        """Gets the secret of the named value specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param named_value_id: Identifier of the NamedValue. Required.
        :type named_value_id: str
        :return: NamedValueSecretContract. The NamedValueSecretContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.NamedValueSecretContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.NamedValueSecretContract] = kwargs.pop("cls", None)

        _request = build_named_value_list_value_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            named_value_id=named_value_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.NamedValueSecretContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    async def _refresh_secret_initial(
        self, resource_group_name: str, service_name: str, named_value_id: str, **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        _request = build_named_value_refresh_secret_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            named_value_id=named_value_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 200:
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if response.status_code == 202:
            response_headers["Azure-AsyncOperation"] = self._deserialize(
                "str", response.headers.get("Azure-AsyncOperation")
            )
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def begin_refresh_secret(
        self, resource_group_name: str, service_name: str, named_value_id: str, **kwargs: Any
    ) -> AsyncLROPoller[_models.NamedValueContract]:
        """Refresh the secret of the named value specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param named_value_id: Identifier of the NamedValue. Required.
        :type named_value_id: str
        :return: An instance of AsyncLROPoller that returns NamedValueContract. The NamedValueContract
         is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.NamedValueContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.NamedValueContract] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._refresh_secret_initial(
                resource_group_name=resource_group_name,
                service_name=service_name,
                named_value_id=named_value_id,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response_headers = {}
            response = pipeline_response.http_response
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

            deserialized = _deserialize(_models.NamedValueContract, response.json())
            if cls:
                return cls(pipeline_response, deserialized, response_headers)  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.NamedValueContract].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.NamedValueContract](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )


class NotificationOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`notification` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self,
        resource_group_name: str,
        service_name: str,
        notification_name: Union[str, _models.NotificationName],
        **kwargs: Any
    ) -> _models.NotificationContract:
        """Gets the details of the Notification specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param notification_name: Notification Name Identifier. Known values are:
         "RequestPublisherNotificationMessage", "PurchasePublisherNotificationMessage",
         "NewApplicationNotificationMessage", "BCC", "NewIssuePublisherNotificationMessage",
         "AccountClosedPublisher", and "QuotaLimitApproachingPublisherNotificationMessage". Required.
        :type notification_name: str or ~azure.mgmt.apimanagement.models.NotificationName
        :return: NotificationContract. The NotificationContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.NotificationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.NotificationContract] = kwargs.pop("cls", None)

        _request = build_notification_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            notification_name=notification_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.NotificationContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        notification_name: Union[str, _models.NotificationName],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.NotificationContract:
        """Create or Update API Management publisher notification.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param notification_name: Notification Name Identifier. Known values are:
         "RequestPublisherNotificationMessage", "PurchasePublisherNotificationMessage",
         "NewApplicationNotificationMessage", "BCC", "NewIssuePublisherNotificationMessage",
         "AccountClosedPublisher", and "QuotaLimitApproachingPublisherNotificationMessage". Required.
        :type notification_name: str or ~azure.mgmt.apimanagement.models.NotificationName
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: NotificationContract. The NotificationContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.NotificationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.NotificationContract] = kwargs.pop("cls", None)

        _request = build_notification_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            notification_name=notification_name,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.NotificationContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.NotificationContract"]:
        """Lists a collection of properties defined within a service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of NotificationContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.NotificationContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.NotificationContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_notification_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.NotificationContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class NotificationRecipientUserOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`notification_recipient_user` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def list_by_notification(
        self,
        resource_group_name: str,
        service_name: str,
        notification_name: Union[str, _models.NotificationName],
        **kwargs: Any
    ) -> _models.RecipientUserCollection:
        """Gets the list of the Notification Recipient User subscribed to the notification.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param notification_name: Notification Name Identifier. Known values are:
         "RequestPublisherNotificationMessage", "PurchasePublisherNotificationMessage",
         "NewApplicationNotificationMessage", "BCC", "NewIssuePublisherNotificationMessage",
         "AccountClosedPublisher", and "QuotaLimitApproachingPublisherNotificationMessage". Required.
        :type notification_name: str or ~azure.mgmt.apimanagement.models.NotificationName
        :return: RecipientUserCollection. The RecipientUserCollection is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.RecipientUserCollection
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.RecipientUserCollection] = kwargs.pop("cls", None)

        _request = build_notification_recipient_user_list_by_notification_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            notification_name=notification_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.RecipientUserCollection, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def check_entity_exists(
        self,
        resource_group_name: str,
        service_name: str,
        notification_name: Union[str, _models.NotificationName],
        user_id: str,
        **kwargs: Any
    ) -> bool:
        """Determine if the Notification Recipient User is subscribed to the notification.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param notification_name: Notification Name Identifier. Known values are:
         "RequestPublisherNotificationMessage", "PurchasePublisherNotificationMessage",
         "NewApplicationNotificationMessage", "BCC", "NewIssuePublisherNotificationMessage",
         "AccountClosedPublisher", and "QuotaLimitApproachingPublisherNotificationMessage". Required.
        :type notification_name: str or ~azure.mgmt.apimanagement.models.NotificationName
        :param user_id: User identifier. Must be unique in the current API Management service instance.
         Required.
        :type user_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_notification_recipient_user_check_entity_exists_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            notification_name=notification_name,
            user_id=user_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [204, 404]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore
        return 200 <= response.status_code <= 299

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        notification_name: Union[str, _models.NotificationName],
        user_id: str,
        **kwargs: Any
    ) -> _models.RecipientUserContract:
        """Adds the API Management User to the list of Recipients for the Notification.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param notification_name: Notification Name Identifier. Known values are:
         "RequestPublisherNotificationMessage", "PurchasePublisherNotificationMessage",
         "NewApplicationNotificationMessage", "BCC", "NewIssuePublisherNotificationMessage",
         "AccountClosedPublisher", and "QuotaLimitApproachingPublisherNotificationMessage". Required.
        :type notification_name: str or ~azure.mgmt.apimanagement.models.NotificationName
        :param user_id: User identifier. Must be unique in the current API Management service instance.
         Required.
        :type user_id: str
        :return: RecipientUserContract. The RecipientUserContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.RecipientUserContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.RecipientUserContract] = kwargs.pop("cls", None)

        _request = build_notification_recipient_user_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            notification_name=notification_name,
            user_id=user_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.RecipientUserContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        notification_name: Union[str, _models.NotificationName],
        user_id: str,
        **kwargs: Any
    ) -> None:
        """Removes the API Management user from the list of Notification.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param notification_name: Notification Name Identifier. Known values are:
         "RequestPublisherNotificationMessage", "PurchasePublisherNotificationMessage",
         "NewApplicationNotificationMessage", "BCC", "NewIssuePublisherNotificationMessage",
         "AccountClosedPublisher", and "QuotaLimitApproachingPublisherNotificationMessage". Required.
        :type notification_name: str or ~azure.mgmt.apimanagement.models.NotificationName
        :param user_id: User identifier. Must be unique in the current API Management service instance.
         Required.
        :type user_id: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_notification_recipient_user_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            notification_name=notification_name,
            user_id=user_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore


class NotificationRecipientEmailOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`notification_recipient_email` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def list_by_notification(
        self,
        resource_group_name: str,
        service_name: str,
        notification_name: Union[str, _models.NotificationName],
        **kwargs: Any
    ) -> _models.RecipientEmailCollection:
        """Gets the list of the Notification Recipient Emails subscribed to a notification.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param notification_name: Notification Name Identifier. Known values are:
         "RequestPublisherNotificationMessage", "PurchasePublisherNotificationMessage",
         "NewApplicationNotificationMessage", "BCC", "NewIssuePublisherNotificationMessage",
         "AccountClosedPublisher", and "QuotaLimitApproachingPublisherNotificationMessage". Required.
        :type notification_name: str or ~azure.mgmt.apimanagement.models.NotificationName
        :return: RecipientEmailCollection. The RecipientEmailCollection is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.RecipientEmailCollection
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.RecipientEmailCollection] = kwargs.pop("cls", None)

        _request = build_notification_recipient_email_list_by_notification_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            notification_name=notification_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.RecipientEmailCollection, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def check_entity_exists(
        self,
        resource_group_name: str,
        service_name: str,
        notification_name: Union[str, _models.NotificationName],
        email: str,
        **kwargs: Any
    ) -> bool:
        """Determine if Notification Recipient Email subscribed to the notification.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param notification_name: Notification Name Identifier. Known values are:
         "RequestPublisherNotificationMessage", "PurchasePublisherNotificationMessage",
         "NewApplicationNotificationMessage", "BCC", "NewIssuePublisherNotificationMessage",
         "AccountClosedPublisher", and "QuotaLimitApproachingPublisherNotificationMessage". Required.
        :type notification_name: str or ~azure.mgmt.apimanagement.models.NotificationName
        :param email: Email identifier. Required.
        :type email: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_notification_recipient_email_check_entity_exists_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            notification_name=notification_name,
            email=email,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [204, 404]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore
        return 200 <= response.status_code <= 299

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        notification_name: Union[str, _models.NotificationName],
        email: str,
        **kwargs: Any
    ) -> _models.RecipientEmailContract:
        """Adds the Email address to the list of Recipients for the Notification.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param notification_name: Notification Name Identifier. Known values are:
         "RequestPublisherNotificationMessage", "PurchasePublisherNotificationMessage",
         "NewApplicationNotificationMessage", "BCC", "NewIssuePublisherNotificationMessage",
         "AccountClosedPublisher", and "QuotaLimitApproachingPublisherNotificationMessage". Required.
        :type notification_name: str or ~azure.mgmt.apimanagement.models.NotificationName
        :param email: Email identifier. Required.
        :type email: str
        :return: RecipientEmailContract. The RecipientEmailContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.RecipientEmailContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.RecipientEmailContract] = kwargs.pop("cls", None)

        _request = build_notification_recipient_email_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            notification_name=notification_name,
            email=email,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.RecipientEmailContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        notification_name: Union[str, _models.NotificationName],
        email: str,
        **kwargs: Any
    ) -> None:
        """Removes the email from the list of Notification.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param notification_name: Notification Name Identifier. Known values are:
         "RequestPublisherNotificationMessage", "PurchasePublisherNotificationMessage",
         "NewApplicationNotificationMessage", "BCC", "NewIssuePublisherNotificationMessage",
         "AccountClosedPublisher", and "QuotaLimitApproachingPublisherNotificationMessage". Required.
        :type notification_name: str or ~azure.mgmt.apimanagement.models.NotificationName
        :param email: Email identifier. Required.
        :type email: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_notification_recipient_email_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            notification_name=notification_name,
            email=email,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore


class WorkspaceNotificationRecipientUserOperations:  # pylint: disable=name-too-long
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`workspace_notification_recipient_user` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def list_by_notification(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        notification_name: Union[str, _models.NotificationName],
        **kwargs: Any
    ) -> _models.RecipientUserCollection:
        """Gets the list of the Notification Recipient User subscribed to the notification.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param notification_name: Notification Name Identifier. Known values are:
         "RequestPublisherNotificationMessage", "PurchasePublisherNotificationMessage",
         "NewApplicationNotificationMessage", "BCC", "NewIssuePublisherNotificationMessage",
         "AccountClosedPublisher", and "QuotaLimitApproachingPublisherNotificationMessage". Required.
        :type notification_name: str or ~azure.mgmt.apimanagement.models.NotificationName
        :return: RecipientUserCollection. The RecipientUserCollection is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.RecipientUserCollection
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.RecipientUserCollection] = kwargs.pop("cls", None)

        _request = build_workspace_notification_recipient_user_list_by_notification_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            notification_name=notification_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.RecipientUserCollection, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def check_entity_exists(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        notification_name: Union[str, _models.NotificationName],
        user_id: str,
        **kwargs: Any
    ) -> bool:
        """Determine if the Notification Recipient User is subscribed to the notification.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param notification_name: Workspace identifier. Must be unique in the current API Management
         service instance. Known values are: "RequestPublisherNotificationMessage",
         "PurchasePublisherNotificationMessage", "NewApplicationNotificationMessage", "BCC",
         "NewIssuePublisherNotificationMessage", "AccountClosedPublisher", and
         "QuotaLimitApproachingPublisherNotificationMessage". Required.
        :type notification_name: str or ~azure.mgmt.apimanagement.models.NotificationName
        :param user_id: User identifier. Must be unique in the current API Management service instance.
         Required.
        :type user_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_notification_recipient_user_check_entity_exists_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            notification_name=notification_name,
            user_id=user_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [204, 404]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore
        return 200 <= response.status_code <= 299

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        notification_name: Union[str, _models.NotificationName],
        user_id: str,
        **kwargs: Any
    ) -> _models.RecipientUserContract:
        """Adds the API Management User to the list of Recipients for the Notification.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param notification_name: Notification Name Identifier. Known values are:
         "RequestPublisherNotificationMessage", "PurchasePublisherNotificationMessage",
         "NewApplicationNotificationMessage", "BCC", "NewIssuePublisherNotificationMessage",
         "AccountClosedPublisher", and "QuotaLimitApproachingPublisherNotificationMessage". Required.
        :type notification_name: str or ~azure.mgmt.apimanagement.models.NotificationName
        :param user_id: User identifier. Must be unique in the current API Management service instance.
         Required.
        :type user_id: str
        :return: RecipientUserContract. The RecipientUserContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.RecipientUserContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.RecipientUserContract] = kwargs.pop("cls", None)

        _request = build_workspace_notification_recipient_user_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            notification_name=notification_name,
            user_id=user_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.RecipientUserContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        notification_name: Union[str, _models.NotificationName],
        user_id: str,
        **kwargs: Any
    ) -> None:
        """Removes the API Management user from the list of Notification.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param notification_name: Workspace identifier. Must be unique in the current API Management
         service instance. Known values are: "RequestPublisherNotificationMessage",
         "PurchasePublisherNotificationMessage", "NewApplicationNotificationMessage", "BCC",
         "NewIssuePublisherNotificationMessage", "AccountClosedPublisher", and
         "QuotaLimitApproachingPublisherNotificationMessage". Required.
        :type notification_name: str or ~azure.mgmt.apimanagement.models.NotificationName
        :param user_id: User identifier. Must be unique in the current API Management service instance.
         Required.
        :type user_id: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_notification_recipient_user_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            notification_name=notification_name,
            user_id=user_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore


class WorkspaceNotificationRecipientEmailOperations:  # pylint: disable=name-too-long
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`workspace_notification_recipient_email` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def list_by_notification(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        notification_name: Union[str, _models.NotificationName],
        **kwargs: Any
    ) -> _models.RecipientEmailCollection:
        """Gets the list of the Notification Recipient Emails subscribed to a notification.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param notification_name: Notification Name Identifier. Known values are:
         "RequestPublisherNotificationMessage", "PurchasePublisherNotificationMessage",
         "NewApplicationNotificationMessage", "BCC", "NewIssuePublisherNotificationMessage",
         "AccountClosedPublisher", and "QuotaLimitApproachingPublisherNotificationMessage". Required.
        :type notification_name: str or ~azure.mgmt.apimanagement.models.NotificationName
        :return: RecipientEmailCollection. The RecipientEmailCollection is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.RecipientEmailCollection
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.RecipientEmailCollection] = kwargs.pop("cls", None)

        _request = build_workspace_notification_recipient_email_list_by_notification_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            notification_name=notification_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.RecipientEmailCollection, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def check_entity_exists(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        notification_name: Union[str, _models.NotificationName],
        email: str,
        **kwargs: Any
    ) -> bool:
        """Determine if Notification Recipient Email subscribed to the notification.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param notification_name: Workspace identifier. Must be unique in the current API Management
         service instance. Known values are: "RequestPublisherNotificationMessage",
         "PurchasePublisherNotificationMessage", "NewApplicationNotificationMessage", "BCC",
         "NewIssuePublisherNotificationMessage", "AccountClosedPublisher", and
         "QuotaLimitApproachingPublisherNotificationMessage". Required.
        :type notification_name: str or ~azure.mgmt.apimanagement.models.NotificationName
        :param email: Email identifier. Required.
        :type email: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_notification_recipient_email_check_entity_exists_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            notification_name=notification_name,
            email=email,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [204, 404]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore
        return 200 <= response.status_code <= 299

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        notification_name: Union[str, _models.NotificationName],
        email: str,
        **kwargs: Any
    ) -> _models.RecipientEmailContract:
        """Adds the Email address to the list of Recipients for the Notification.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param notification_name: Notification Name Identifier. Known values are:
         "RequestPublisherNotificationMessage", "PurchasePublisherNotificationMessage",
         "NewApplicationNotificationMessage", "BCC", "NewIssuePublisherNotificationMessage",
         "AccountClosedPublisher", and "QuotaLimitApproachingPublisherNotificationMessage". Required.
        :type notification_name: str or ~azure.mgmt.apimanagement.models.NotificationName
        :param email: Email identifier. Required.
        :type email: str
        :return: RecipientEmailContract. The RecipientEmailContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.RecipientEmailContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.RecipientEmailContract] = kwargs.pop("cls", None)

        _request = build_workspace_notification_recipient_email_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            notification_name=notification_name,
            email=email,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.RecipientEmailContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        notification_name: Union[str, _models.NotificationName],
        email: str,
        **kwargs: Any
    ) -> None:
        """Removes the email from the list of Notification.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param notification_name: Workspace identifier. Must be unique in the current API Management
         service instance. Known values are: "RequestPublisherNotificationMessage",
         "PurchasePublisherNotificationMessage", "NewApplicationNotificationMessage", "BCC",
         "NewIssuePublisherNotificationMessage", "AccountClosedPublisher", and
         "QuotaLimitApproachingPublisherNotificationMessage". Required.
        :type notification_name: str or ~azure.mgmt.apimanagement.models.NotificationName
        :param email: Email identifier. Required.
        :type email: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_notification_recipient_email_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            notification_name=notification_name,
            email=email,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore


class OpenIdConnectProviderOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`open_id_connect_provider` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, opid: str, **kwargs: Any
    ) -> _models.OpenidConnectProviderContract:
        """Gets specific OpenID Connect Provider without secrets.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param opid: Identifier of the OpenID Connect Provider. Required.
        :type opid: str
        :return: OpenidConnectProviderContract. The OpenidConnectProviderContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.OpenidConnectProviderContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.OpenidConnectProviderContract] = kwargs.pop("cls", None)

        _request = build_open_id_connect_provider_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            opid=opid,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.OpenidConnectProviderContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(self, resource_group_name: str, service_name: str, opid: str, **kwargs: Any) -> bool:
        """Gets the entity state (Etag) version of the openIdConnectProvider specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param opid: Identifier of the OpenID Connect Provider. Required.
        :type opid: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_open_id_connect_provider_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            opid=opid,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        opid: str,
        parameters: _models.OpenidConnectProviderContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.OpenidConnectProviderContract:
        """Creates or updates the OpenID Connect Provider.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param opid: Identifier of the OpenID Connect Provider. Required.
        :type opid: str
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.OpenidConnectProviderContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: OpenidConnectProviderContract. The OpenidConnectProviderContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.OpenidConnectProviderContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        opid: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.OpenidConnectProviderContract:
        """Creates or updates the OpenID Connect Provider.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param opid: Identifier of the OpenID Connect Provider. Required.
        :type opid: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: OpenidConnectProviderContract. The OpenidConnectProviderContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.OpenidConnectProviderContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        opid: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.OpenidConnectProviderContract:
        """Creates or updates the OpenID Connect Provider.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param opid: Identifier of the OpenID Connect Provider. Required.
        :type opid: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: OpenidConnectProviderContract. The OpenidConnectProviderContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.OpenidConnectProviderContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        opid: str,
        parameters: Union[_models.OpenidConnectProviderContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.OpenidConnectProviderContract:
        """Creates or updates the OpenID Connect Provider.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param opid: Identifier of the OpenID Connect Provider. Required.
        :type opid: str
        :param parameters: Create parameters. Is one of the following types:
         OpenidConnectProviderContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.OpenidConnectProviderContract or JSON or
         IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: OpenidConnectProviderContract. The OpenidConnectProviderContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.OpenidConnectProviderContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.OpenidConnectProviderContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_open_id_connect_provider_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            opid=opid,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.OpenidConnectProviderContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        opid: str,
        parameters: _models.OpenidConnectProviderUpdateContract,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.OpenidConnectProviderContract:
        """Updates the specific OpenID Connect Provider.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param opid: Identifier of the OpenID Connect Provider. Required.
        :type opid: str
        :param parameters: Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.OpenidConnectProviderUpdateContract
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: OpenidConnectProviderContract. The OpenidConnectProviderContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.OpenidConnectProviderContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        opid: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.OpenidConnectProviderContract:
        """Updates the specific OpenID Connect Provider.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param opid: Identifier of the OpenID Connect Provider. Required.
        :type opid: str
        :param parameters: Update parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: OpenidConnectProviderContract. The OpenidConnectProviderContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.OpenidConnectProviderContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        opid: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.OpenidConnectProviderContract:
        """Updates the specific OpenID Connect Provider.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param opid: Identifier of the OpenID Connect Provider. Required.
        :type opid: str
        :param parameters: Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: OpenidConnectProviderContract. The OpenidConnectProviderContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.OpenidConnectProviderContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        opid: str,
        parameters: Union[_models.OpenidConnectProviderUpdateContract, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.OpenidConnectProviderContract:
        """Updates the specific OpenID Connect Provider.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param opid: Identifier of the OpenID Connect Provider. Required.
        :type opid: str
        :param parameters: Update parameters. Is one of the following types:
         OpenidConnectProviderUpdateContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.OpenidConnectProviderUpdateContract or JSON
         or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: OpenidConnectProviderContract. The OpenidConnectProviderContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.OpenidConnectProviderContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.OpenidConnectProviderContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_open_id_connect_provider_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            opid=opid,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.OpenidConnectProviderContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        opid: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes specific OpenID Connect Provider of the API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param opid: Identifier of the OpenID Connect Provider. Required.
        :type opid: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_open_id_connect_provider_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            opid=opid,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.OpenidConnectProviderContract"]:
        """Lists of all the OpenId Connect Providers.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         displayName | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of OpenidConnectProviderContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.OpenidConnectProviderContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.OpenidConnectProviderContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_open_id_connect_provider_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.OpenidConnectProviderContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def list_secrets(
        self, resource_group_name: str, service_name: str, opid: str, **kwargs: Any
    ) -> _models.ClientSecretContract:
        """Gets the client secret details of the OpenID Connect Provider.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param opid: Identifier of the OpenID Connect Provider. Required.
        :type opid: str
        :return: ClientSecretContract. The ClientSecretContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ClientSecretContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ClientSecretContract] = kwargs.pop("cls", None)

        _request = build_open_id_connect_provider_list_secrets_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            opid=opid,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ClientSecretContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore


class PolicyFragmentOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`policy_fragment` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self,
        resource_group_name: str,
        service_name: str,
        id: str,
        *,
        format: Optional[Union[str, _models.PolicyFragmentContentFormat]] = None,
        **kwargs: Any
    ) -> _models.PolicyFragmentContract:
        """Gets a policy fragment.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param id: A resource identifier. Required.
        :type id: str
        :keyword format: Policy fragment content format. Known values are: "xml" and "rawxml". Default
         value is None.
        :paramtype format: str or ~azure.mgmt.apimanagement.models.PolicyFragmentContentFormat
        :return: PolicyFragmentContract. The PolicyFragmentContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyFragmentContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.PolicyFragmentContract] = kwargs.pop("cls", None)

        _request = build_policy_fragment_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            id=id,
            subscription_id=self._config.subscription_id,
            format=format,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PolicyFragmentContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(self, resource_group_name: str, service_name: str, id: str, **kwargs: Any) -> bool:
        """Gets the entity state (Etag) version of a policy fragment.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param id: A resource identifier. Required.
        :type id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_policy_fragment_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            id=id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    async def _create_or_update_initial(
        self,
        resource_group_name: str,
        service_name: str,
        id: str,
        parameters: Union[_models.PolicyFragmentContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_policy_fragment_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            id=id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["Azure-AsyncOperation"] = self._deserialize(
            "str", response.headers.get("Azure-AsyncOperation")
        )
        response_headers["location"] = self._deserialize("str", response.headers.get("location"))
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        id: str,
        parameters: _models.PolicyFragmentContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.PolicyFragmentContract]:
        """Creates or updates a policy fragment.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param id: A resource identifier. Required.
        :type id: str
        :param parameters: The policy fragment contents to apply. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PolicyFragmentContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns PolicyFragmentContract. The
         PolicyFragmentContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.PolicyFragmentContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.PolicyFragmentContract]:
        """Creates or updates a policy fragment.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param id: A resource identifier. Required.
        :type id: str
        :param parameters: The policy fragment contents to apply. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns PolicyFragmentContract. The
         PolicyFragmentContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.PolicyFragmentContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.PolicyFragmentContract]:
        """Creates or updates a policy fragment.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param id: A resource identifier. Required.
        :type id: str
        :param parameters: The policy fragment contents to apply. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns PolicyFragmentContract. The
         PolicyFragmentContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.PolicyFragmentContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        id: str,
        parameters: Union[_models.PolicyFragmentContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.PolicyFragmentContract]:
        """Creates or updates a policy fragment.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param id: A resource identifier. Required.
        :type id: str
        :param parameters: The policy fragment contents to apply. Is one of the following types:
         PolicyFragmentContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PolicyFragmentContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns PolicyFragmentContract. The
         PolicyFragmentContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.PolicyFragmentContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.PolicyFragmentContract] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._create_or_update_initial(
                resource_group_name=resource_group_name,
                service_name=service_name,
                id=id,
                parameters=parameters,
                etag=etag,
                match_condition=match_condition,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response_headers = {}
            response = pipeline_response.http_response
            response_headers["Azure-AsyncOperation"] = self._deserialize(
                "str", response.headers.get("Azure-AsyncOperation")
            )
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

            deserialized = _deserialize(_models.PolicyFragmentContract, response.json())
            if cls:
                return cls(pipeline_response, deserialized, response_headers)  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.PolicyFragmentContract].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.PolicyFragmentContract](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes a policy fragment.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param id: A resource identifier. Required.
        :type id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_policy_fragment_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            id=id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        filter: Optional[str] = None,
        orderby: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.PolicyFragmentContract"]:
        """Gets all policy fragments.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter, orderBy | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         description | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>| value | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>. Default value is None.
        :paramtype filter: str
        :keyword orderby: OData order by query option. Default value is None.
        :paramtype orderby: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of PolicyFragmentContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.PolicyFragmentContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.PolicyFragmentContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_policy_fragment_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    orderby=orderby,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.PolicyFragmentContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def list_references(
        self,
        resource_group_name: str,
        service_name: str,
        id: str,
        *,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> _models.ResourceCollection:
        """Lists policy resources that reference the policy fragment.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param id: A resource identifier. Required.
        :type id: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: ResourceCollection. The ResourceCollection is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ResourceCollection
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ResourceCollection] = kwargs.pop("cls", None)

        _request = build_policy_fragment_list_references_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            id=id,
            subscription_id=self._config.subscription_id,
            top=top,
            skip=skip,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ResourceCollection, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class PolicyRestrictionOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`policy_restriction` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, policy_restriction_id: str, **kwargs: Any
    ) -> _models.PolicyRestrictionContract:
        """Get the policy restriction of the Api Management service.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param policy_restriction_id: Policy restrictions after an entity level. Required.
        :type policy_restriction_id: str
        :return: PolicyRestrictionContract. The PolicyRestrictionContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyRestrictionContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.PolicyRestrictionContract] = kwargs.pop("cls", None)

        _request = build_policy_restriction_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            policy_restriction_id=policy_restriction_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PolicyRestrictionContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, policy_restriction_id: str, **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the policy restriction in the Api Management service.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param policy_restriction_id: Policy restrictions after an entity level. Required.
        :type policy_restriction_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_policy_restriction_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            policy_restriction_id=policy_restriction_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        policy_restriction_id: str,
        parameters: _models.PolicyRestrictionContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyRestrictionContract:
        """Creates or updates the policy restriction configuration of the Api Management service.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param policy_restriction_id: Policy restrictions after an entity level. Required.
        :type policy_restriction_id: str
        :param parameters: The policy restriction to apply. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PolicyRestrictionContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyRestrictionContract. The PolicyRestrictionContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyRestrictionContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        policy_restriction_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyRestrictionContract:
        """Creates or updates the policy restriction configuration of the Api Management service.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param policy_restriction_id: Policy restrictions after an entity level. Required.
        :type policy_restriction_id: str
        :param parameters: The policy restriction to apply. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyRestrictionContract. The PolicyRestrictionContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyRestrictionContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        policy_restriction_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyRestrictionContract:
        """Creates or updates the policy restriction configuration of the Api Management service.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param policy_restriction_id: Policy restrictions after an entity level. Required.
        :type policy_restriction_id: str
        :param parameters: The policy restriction to apply. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyRestrictionContract. The PolicyRestrictionContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyRestrictionContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        policy_restriction_id: str,
        parameters: Union[_models.PolicyRestrictionContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.PolicyRestrictionContract:
        """Creates or updates the policy restriction configuration of the Api Management service.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param policy_restriction_id: Policy restrictions after an entity level. Required.
        :type policy_restriction_id: str
        :param parameters: The policy restriction to apply. Is one of the following types:
         PolicyRestrictionContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PolicyRestrictionContract or JSON or
         IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyRestrictionContract. The PolicyRestrictionContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyRestrictionContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.PolicyRestrictionContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_policy_restriction_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            policy_restriction_id=policy_restriction_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PolicyRestrictionContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        policy_restriction_id: str,
        parameters: _models.PolicyRestrictionUpdateContract,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.PolicyRestrictionContract:
        """Updates the policy restriction configuration of the Api Management service.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param policy_restriction_id: Policy restrictions after an entity level. Required.
        :type policy_restriction_id: str
        :param parameters: The policy restriction to apply. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PolicyRestrictionUpdateContract
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: PolicyRestrictionContract. The PolicyRestrictionContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyRestrictionContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        policy_restriction_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.PolicyRestrictionContract:
        """Updates the policy restriction configuration of the Api Management service.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param policy_restriction_id: Policy restrictions after an entity level. Required.
        :type policy_restriction_id: str
        :param parameters: The policy restriction to apply. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: PolicyRestrictionContract. The PolicyRestrictionContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyRestrictionContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        policy_restriction_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.PolicyRestrictionContract:
        """Updates the policy restriction configuration of the Api Management service.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param policy_restriction_id: Policy restrictions after an entity level. Required.
        :type policy_restriction_id: str
        :param parameters: The policy restriction to apply. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: PolicyRestrictionContract. The PolicyRestrictionContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyRestrictionContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        policy_restriction_id: str,
        parameters: Union[_models.PolicyRestrictionUpdateContract, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.PolicyRestrictionContract:
        """Updates the policy restriction configuration of the Api Management service.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param policy_restriction_id: Policy restrictions after an entity level. Required.
        :type policy_restriction_id: str
        :param parameters: The policy restriction to apply. Is one of the following types:
         PolicyRestrictionUpdateContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PolicyRestrictionUpdateContract or JSON or
         IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PolicyRestrictionContract. The PolicyRestrictionContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PolicyRestrictionContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.PolicyRestrictionContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_policy_restriction_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            policy_restriction_id=policy_restriction_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PolicyRestrictionContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        policy_restriction_id: str,
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> None:
        """Deletes the policy restriction configuration of the Api Management Service.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param policy_restriction_id: Policy restrictions after an entity level. Required.
        :type policy_restriction_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_policy_restriction_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            policy_restriction_id=policy_restriction_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self, resource_group_name: str, service_name: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.PolicyRestrictionContract"]:
        """Gets all policy restrictions of API Management services.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :return: An iterator like instance of PolicyRestrictionContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.PolicyRestrictionContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.PolicyRestrictionContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_policy_restriction_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.PolicyRestrictionContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class PortalConfigOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`portal_config` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, portal_config_id: str, **kwargs: Any
    ) -> _models.PortalConfigContract:
        """Get the developer portal configuration.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param portal_config_id: Portal configuration identifier. Required.
        :type portal_config_id: str
        :return: PortalConfigContract. The PortalConfigContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PortalConfigContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.PortalConfigContract] = kwargs.pop("cls", None)

        _request = build_portal_config_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            portal_config_id=portal_config_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PortalConfigContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, portal_config_id: str, **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the developer portal configuration.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param portal_config_id: Portal configuration identifier. Required.
        :type portal_config_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_portal_config_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            portal_config_id=portal_config_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        portal_config_id: str,
        parameters: _models.PortalConfigContract,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.PortalConfigContract:
        """Create or update the developer portal configuration.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param portal_config_id: Portal configuration identifier. Required.
        :type portal_config_id: str
        :param parameters: Update the developer portal configuration. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PortalConfigContract
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: PortalConfigContract. The PortalConfigContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PortalConfigContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        portal_config_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.PortalConfigContract:
        """Create or update the developer portal configuration.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param portal_config_id: Portal configuration identifier. Required.
        :type portal_config_id: str
        :param parameters: Update the developer portal configuration. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: PortalConfigContract. The PortalConfigContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PortalConfigContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        portal_config_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.PortalConfigContract:
        """Create or update the developer portal configuration.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param portal_config_id: Portal configuration identifier. Required.
        :type portal_config_id: str
        :param parameters: Update the developer portal configuration. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: PortalConfigContract. The PortalConfigContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PortalConfigContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        portal_config_id: str,
        parameters: Union[_models.PortalConfigContract, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.PortalConfigContract:
        """Create or update the developer portal configuration.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param portal_config_id: Portal configuration identifier. Required.
        :type portal_config_id: str
        :param parameters: Update the developer portal configuration. Is one of the following types:
         PortalConfigContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PortalConfigContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PortalConfigContract. The PortalConfigContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PortalConfigContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.PortalConfigContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_portal_config_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            portal_config_id=portal_config_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PortalConfigContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        portal_config_id: str,
        parameters: _models.PortalConfigContract,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.PortalConfigContract:
        """Update the developer portal configuration.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param portal_config_id: Portal configuration identifier. Required.
        :type portal_config_id: str
        :param parameters: Update the developer portal configuration. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PortalConfigContract
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: PortalConfigContract. The PortalConfigContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PortalConfigContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        portal_config_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.PortalConfigContract:
        """Update the developer portal configuration.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param portal_config_id: Portal configuration identifier. Required.
        :type portal_config_id: str
        :param parameters: Update the developer portal configuration. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: PortalConfigContract. The PortalConfigContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PortalConfigContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        portal_config_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.PortalConfigContract:
        """Update the developer portal configuration.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param portal_config_id: Portal configuration identifier. Required.
        :type portal_config_id: str
        :param parameters: Update the developer portal configuration. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: PortalConfigContract. The PortalConfigContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PortalConfigContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        portal_config_id: str,
        parameters: Union[_models.PortalConfigContract, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.PortalConfigContract:
        """Update the developer portal configuration.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param portal_config_id: Portal configuration identifier. Required.
        :type portal_config_id: str
        :param parameters: Update the developer portal configuration. Is one of the following types:
         PortalConfigContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PortalConfigContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: PortalConfigContract. The PortalConfigContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PortalConfigContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.PortalConfigContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_portal_config_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            portal_config_id=portal_config_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PortalConfigContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list_by_service(
        self, resource_group_name: str, service_name: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.PortalConfigContract"]:
        """Lists the developer portal configurations.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :return: An iterator like instance of PortalConfigContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.PortalConfigContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.PortalConfigContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_portal_config_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.PortalConfigContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class ClientApplicationOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`client_application` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, client_application_id: str, **kwargs: Any
    ) -> _models.ClientApplicationContract:
        """Gets the details of the client application specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param client_application_id: Client Application identifier. Must be unique in the current API
         Management service instance. Required.
        :type client_application_id: str
        :return: ClientApplicationContract. The ClientApplicationContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ClientApplicationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ClientApplicationContract] = kwargs.pop("cls", None)

        _request = build_client_application_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            client_application_id=client_application_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ClientApplicationContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, client_application_id: str, **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the product specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param client_application_id: Client Application identifier. Must be unique in the current API
         Management service instance. Required.
        :type client_application_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_client_application_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            client_application_id=client_application_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        client_application_id: str,
        parameters: _models.ClientApplicationContract,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ClientApplicationContract:
        """Creates or Updates a client application.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param client_application_id: Client Application identifier. Must be unique in the current API
         Management service instance. Required.
        :type client_application_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ClientApplicationContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ClientApplicationContract. The ClientApplicationContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ClientApplicationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        client_application_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ClientApplicationContract:
        """Creates or Updates a client application.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param client_application_id: Client Application identifier. Must be unique in the current API
         Management service instance. Required.
        :type client_application_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ClientApplicationContract. The ClientApplicationContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ClientApplicationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        client_application_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ClientApplicationContract:
        """Creates or Updates a client application.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param client_application_id: Client Application identifier. Must be unique in the current API
         Management service instance. Required.
        :type client_application_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ClientApplicationContract. The ClientApplicationContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ClientApplicationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        client_application_id: str,
        parameters: Union[_models.ClientApplicationContract, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.ClientApplicationContract:
        """Creates or Updates a client application.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param client_application_id: Client Application identifier. Must be unique in the current API
         Management service instance. Required.
        :type client_application_id: str
        :param parameters: Create or update parameters. Is one of the following types:
         ClientApplicationContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ClientApplicationContract or JSON or
         IO[bytes]
        :return: ClientApplicationContract. The ClientApplicationContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ClientApplicationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ClientApplicationContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_client_application_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            client_application_id=client_application_id,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ClientApplicationContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self, resource_group_name: str, service_name: str, client_application_id: str, **kwargs: Any
    ) -> None:
        """Delete client application.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param client_application_id: Client Application identifier. Must be unique in the current API
         Management service instance. Required.
        :type client_application_id: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_client_application_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            client_application_id=client_application_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.ClientApplicationContract"]:
        """Lists a collection of client applications in the specified service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| displayName
         | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         description | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br> state | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>|. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of ClientApplicationContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ClientApplicationContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ClientApplicationContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_client_application_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ClientApplicationContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def list_secrets(
        self, resource_group_name: str, service_name: str, client_application_id: str, **kwargs: Any
    ) -> _models.ClientApplicationSecretsContract:
        """Retrived client application secrets.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param client_application_id: Client Application identifier. Must be unique in the current API
         Management service instance. Required.
        :type client_application_id: str
        :return: ClientApplicationSecretsContract. The ClientApplicationSecretsContract is compatible
         with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ClientApplicationSecretsContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ClientApplicationSecretsContract] = kwargs.pop("cls", None)

        _request = build_client_application_list_secrets_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            client_application_id=client_application_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ClientApplicationSecretsContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class ClientApplicationProductLinkOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`client_application_product_link` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self,
        resource_group_name: str,
        service_name: str,
        client_application_id: str,
        client_application_product_link_id: str,
        **kwargs: Any
    ) -> _models.ClientApplicationProductLinkContract:
        """Gets the product link for the client application.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param client_application_id: Client Application identifier. Must be unique in the current API
         Management service instance. Required.
        :type client_application_id: str
        :param client_application_product_link_id: Client Application Product Link identifier. Must be
         unique in the current API Management service instance. Required.
        :type client_application_product_link_id: str
        :return: ClientApplicationProductLinkContract. The ClientApplicationProductLinkContract is
         compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ClientApplicationProductLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ClientApplicationProductLinkContract] = kwargs.pop("cls", None)

        _request = build_client_application_product_link_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            client_application_id=client_application_id,
            client_application_product_link_id=client_application_product_link_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ClientApplicationProductLinkContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def create(
        self,
        resource_group_name: str,
        service_name: str,
        client_application_id: str,
        client_application_product_link_id: str,
        parameters: _models.ClientApplicationProductLinkContract,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ClientApplicationProductLinkContract:
        """Adds an Product to the specified Client Application via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param client_application_id: Client Application identifier. Must be unique in the current API
         Management service instance. Required.
        :type client_application_id: str
        :param client_application_product_link_id: Client Application Product Link identifier. Must be
         unique in the current API Management service instance. Required.
        :type client_application_product_link_id: str
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ClientApplicationProductLinkContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ClientApplicationProductLinkContract. The ClientApplicationProductLinkContract is
         compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ClientApplicationProductLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create(
        self,
        resource_group_name: str,
        service_name: str,
        client_application_id: str,
        client_application_product_link_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ClientApplicationProductLinkContract:
        """Adds an Product to the specified Client Application via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param client_application_id: Client Application identifier. Must be unique in the current API
         Management service instance. Required.
        :type client_application_id: str
        :param client_application_product_link_id: Client Application Product Link identifier. Must be
         unique in the current API Management service instance. Required.
        :type client_application_product_link_id: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ClientApplicationProductLinkContract. The ClientApplicationProductLinkContract is
         compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ClientApplicationProductLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create(
        self,
        resource_group_name: str,
        service_name: str,
        client_application_id: str,
        client_application_product_link_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ClientApplicationProductLinkContract:
        """Adds an Product to the specified Client Application via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param client_application_id: Client Application identifier. Must be unique in the current API
         Management service instance. Required.
        :type client_application_id: str
        :param client_application_product_link_id: Client Application Product Link identifier. Must be
         unique in the current API Management service instance. Required.
        :type client_application_product_link_id: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ClientApplicationProductLinkContract. The ClientApplicationProductLinkContract is
         compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ClientApplicationProductLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create(
        self,
        resource_group_name: str,
        service_name: str,
        client_application_id: str,
        client_application_product_link_id: str,
        parameters: Union[_models.ClientApplicationProductLinkContract, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.ClientApplicationProductLinkContract:
        """Adds an Product to the specified Client Application via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param client_application_id: Client Application identifier. Must be unique in the current API
         Management service instance. Required.
        :type client_application_id: str
        :param client_application_product_link_id: Client Application Product Link identifier. Must be
         unique in the current API Management service instance. Required.
        :type client_application_product_link_id: str
        :param parameters: Create parameters. Is one of the following types:
         ClientApplicationProductLinkContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ClientApplicationProductLinkContract or JSON
         or IO[bytes]
        :return: ClientApplicationProductLinkContract. The ClientApplicationProductLinkContract is
         compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ClientApplicationProductLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ClientApplicationProductLinkContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_client_application_product_link_create_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            client_application_id=client_application_id,
            client_application_product_link_id=client_application_product_link_id,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ClientApplicationProductLinkContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        client_application_id: str,
        client_application_product_link_id: str,
        **kwargs: Any
    ) -> None:
        """Deletes the specified Product from the specified client application.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param client_application_id: Client Application identifier. Must be unique in the current API
         Management service instance. Required.
        :type client_application_id: str
        :param client_application_product_link_id: Client Application Product Link identifier. Must be
         unique in the current API Management service instance. Required.
        :type client_application_product_link_id: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_client_application_product_link_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            client_application_id=client_application_id,
            client_application_product_link_id=client_application_product_link_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_client_applications(
        self,
        resource_group_name: str,
        service_name: str,
        client_application_id: str,
        *,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.ClientApplicationProductLinkContract"]:
        """Lists a collection of product links associated with the specified client application.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param client_application_id: Client Application identifier. Must be unique in the current API
         Management service instance. Required.
        :type client_application_id: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of ClientApplicationProductLinkContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ClientApplicationProductLinkContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ClientApplicationProductLinkContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_client_application_product_link_list_by_client_applications_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    client_application_id=client_application_id,
                    subscription_id=self._config.subscription_id,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ClientApplicationProductLinkContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class PortalRevisionOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`portal_revision` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, portal_revision_id: str, **kwargs: Any
    ) -> _models.PortalRevisionContract:
        """Gets the developer portal's revision specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param portal_revision_id: Portal revision identifier. Must be unique in the current API
         Management service instance. Required.
        :type portal_revision_id: str
        :return: PortalRevisionContract. The PortalRevisionContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PortalRevisionContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.PortalRevisionContract] = kwargs.pop("cls", None)

        _request = build_portal_revision_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            portal_revision_id=portal_revision_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PortalRevisionContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, portal_revision_id: str, **kwargs: Any
    ) -> bool:
        """Gets the developer portal revision specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param portal_revision_id: Portal revision identifier. Must be unique in the current API
         Management service instance. Required.
        :type portal_revision_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_portal_revision_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            portal_revision_id=portal_revision_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    async def _create_or_update_initial(
        self,
        resource_group_name: str,
        service_name: str,
        portal_revision_id: str,
        parameters: Union[_models.PortalRevisionContract, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_portal_revision_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            portal_revision_id=portal_revision_id,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [201]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["Azure-AsyncOperation"] = self._deserialize(
            "str", response.headers.get("Azure-AsyncOperation")
        )
        response_headers["location"] = self._deserialize("str", response.headers.get("location"))
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        portal_revision_id: str,
        parameters: _models.PortalRevisionContract,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.PortalRevisionContract]:
        """Creates a new developer portal's revision by running the portal's publishing. The ``isCurrent``
        property indicates if the revision is publicly accessible.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param portal_revision_id: Portal revision identifier. Must be unique in the current API
         Management service instance. Required.
        :type portal_revision_id: str
        :param parameters: Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PortalRevisionContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns PortalRevisionContract. The
         PortalRevisionContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.PortalRevisionContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        portal_revision_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.PortalRevisionContract]:
        """Creates a new developer portal's revision by running the portal's publishing. The ``isCurrent``
        property indicates if the revision is publicly accessible.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param portal_revision_id: Portal revision identifier. Must be unique in the current API
         Management service instance. Required.
        :type portal_revision_id: str
        :param parameters: Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns PortalRevisionContract. The
         PortalRevisionContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.PortalRevisionContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        portal_revision_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.PortalRevisionContract]:
        """Creates a new developer portal's revision by running the portal's publishing. The ``isCurrent``
        property indicates if the revision is publicly accessible.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param portal_revision_id: Portal revision identifier. Must be unique in the current API
         Management service instance. Required.
        :type portal_revision_id: str
        :param parameters: Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns PortalRevisionContract. The
         PortalRevisionContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.PortalRevisionContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        portal_revision_id: str,
        parameters: Union[_models.PortalRevisionContract, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.PortalRevisionContract]:
        """Creates a new developer portal's revision by running the portal's publishing. The ``isCurrent``
        property indicates if the revision is publicly accessible.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param portal_revision_id: Portal revision identifier. Must be unique in the current API
         Management service instance. Required.
        :type portal_revision_id: str
        :param parameters: Is one of the following types: PortalRevisionContract, JSON, IO[bytes]
         Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PortalRevisionContract or JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns PortalRevisionContract. The
         PortalRevisionContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.PortalRevisionContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.PortalRevisionContract] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._create_or_update_initial(
                resource_group_name=resource_group_name,
                service_name=service_name,
                portal_revision_id=portal_revision_id,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response_headers = {}
            response = pipeline_response.http_response
            response_headers["Azure-AsyncOperation"] = self._deserialize(
                "str", response.headers.get("Azure-AsyncOperation")
            )
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

            deserialized = _deserialize(_models.PortalRevisionContract, response.json())
            if cls:
                return cls(pipeline_response, deserialized, response_headers)  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.PortalRevisionContract].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.PortalRevisionContract](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _update_initial(
        self,
        resource_group_name: str,
        service_name: str,
        portal_revision_id: str,
        parameters: Union[_models.PortalRevisionContract, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_portal_revision_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            portal_revision_id=portal_revision_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 200:
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if response.status_code == 202:
            response_headers["Azure-AsyncOperation"] = self._deserialize(
                "str", response.headers.get("Azure-AsyncOperation")
            )
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_update(
        self,
        resource_group_name: str,
        service_name: str,
        portal_revision_id: str,
        parameters: _models.PortalRevisionContract,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.PortalRevisionContract]:
        """Updates the description of specified portal revision or makes it current.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param portal_revision_id: Portal revision identifier. Must be unique in the current API
         Management service instance. Required.
        :type portal_revision_id: str
        :param parameters: Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PortalRevisionContract
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns PortalRevisionContract. The
         PortalRevisionContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.PortalRevisionContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_update(
        self,
        resource_group_name: str,
        service_name: str,
        portal_revision_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.PortalRevisionContract]:
        """Updates the description of specified portal revision or makes it current.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param portal_revision_id: Portal revision identifier. Must be unique in the current API
         Management service instance. Required.
        :type portal_revision_id: str
        :param parameters: Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns PortalRevisionContract. The
         PortalRevisionContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.PortalRevisionContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_update(
        self,
        resource_group_name: str,
        service_name: str,
        portal_revision_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.PortalRevisionContract]:
        """Updates the description of specified portal revision or makes it current.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param portal_revision_id: Portal revision identifier. Must be unique in the current API
         Management service instance. Required.
        :type portal_revision_id: str
        :param parameters: Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns PortalRevisionContract. The
         PortalRevisionContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.PortalRevisionContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_update(
        self,
        resource_group_name: str,
        service_name: str,
        portal_revision_id: str,
        parameters: Union[_models.PortalRevisionContract, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.PortalRevisionContract]:
        """Updates the description of specified portal revision or makes it current.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param portal_revision_id: Portal revision identifier. Must be unique in the current API
         Management service instance. Required.
        :type portal_revision_id: str
        :param parameters: Is one of the following types: PortalRevisionContract, JSON, IO[bytes]
         Required.
        :type parameters: ~azure.mgmt.apimanagement.models.PortalRevisionContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns PortalRevisionContract. The
         PortalRevisionContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.PortalRevisionContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.PortalRevisionContract] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._update_initial(
                resource_group_name=resource_group_name,
                service_name=service_name,
                portal_revision_id=portal_revision_id,
                parameters=parameters,
                etag=etag,
                match_condition=match_condition,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response_headers = {}
            response = pipeline_response.http_response
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

            deserialized = _deserialize(_models.PortalRevisionContract, response.json())
            if cls:
                return cls(pipeline_response, deserialized, response_headers)  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.PortalRevisionContract].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.PortalRevisionContract](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.PortalRevisionContract"]:
        """Lists developer portal's revisions.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: | Field       | Supported operators    | Supported functions               |
         |-------------|------------------------|-----------------------------------|

         |name | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith|
         |description | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith|
         |isCurrent | eq, ne |    |. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of PortalRevisionContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.PortalRevisionContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.PortalRevisionContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_portal_revision_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.PortalRevisionContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class PrivateEndpointConnectionOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`private_endpoint_connection` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get_by_name(
        self, resource_group_name: str, service_name: str, private_endpoint_connection_name: str, **kwargs: Any
    ) -> _models.PrivateEndpointConnection:
        """Gets the details of the Private Endpoint Connection specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param private_endpoint_connection_name: The name of the private endpoint connection associated
         with the Azure resource. Required.
        :type private_endpoint_connection_name: str
        :return: PrivateEndpointConnection. The PrivateEndpointConnection is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PrivateEndpointConnection
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None)

        _request = build_private_endpoint_connection_get_by_name_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            private_endpoint_connection_name=private_endpoint_connection_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PrivateEndpointConnection, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    async def _create_or_update_initial(
        self,
        resource_group_name: str,
        service_name: str,
        private_endpoint_connection_name: str,
        private_endpoint_connection_request: Union[_models.PrivateEndpointConnectionRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(private_endpoint_connection_request, (IOBase, bytes)):
            _content = private_endpoint_connection_request
        else:
            _content = json.dumps(private_endpoint_connection_request, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_private_endpoint_connection_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            private_endpoint_connection_name=private_endpoint_connection_name,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        private_endpoint_connection_name: str,
        private_endpoint_connection_request: _models.PrivateEndpointConnectionRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.PrivateEndpointConnection]:
        """Creates a new Private Endpoint Connection or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param private_endpoint_connection_name: API revision identifier. Must be unique in the current
         API Management service instance. Non-current revision has ;rev=n as a suffix where n is the
         revision number. Required.
        :type private_endpoint_connection_name: str
        :param private_endpoint_connection_request: Required.
        :type private_endpoint_connection_request:
         ~azure.mgmt.apimanagement.models.PrivateEndpointConnectionRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns PrivateEndpointConnection. The
         PrivateEndpointConnection is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.PrivateEndpointConnection]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        private_endpoint_connection_name: str,
        private_endpoint_connection_request: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.PrivateEndpointConnection]:
        """Creates a new Private Endpoint Connection or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param private_endpoint_connection_name: API revision identifier. Must be unique in the current
         API Management service instance. Non-current revision has ;rev=n as a suffix where n is the
         revision number. Required.
        :type private_endpoint_connection_name: str
        :param private_endpoint_connection_request: Required.
        :type private_endpoint_connection_request: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns PrivateEndpointConnection. The
         PrivateEndpointConnection is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.PrivateEndpointConnection]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        private_endpoint_connection_name: str,
        private_endpoint_connection_request: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.PrivateEndpointConnection]:
        """Creates a new Private Endpoint Connection or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param private_endpoint_connection_name: API revision identifier. Must be unique in the current
         API Management service instance. Non-current revision has ;rev=n as a suffix where n is the
         revision number. Required.
        :type private_endpoint_connection_name: str
        :param private_endpoint_connection_request: Required.
        :type private_endpoint_connection_request: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns PrivateEndpointConnection. The
         PrivateEndpointConnection is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.PrivateEndpointConnection]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        private_endpoint_connection_name: str,
        private_endpoint_connection_request: Union[_models.PrivateEndpointConnectionRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.PrivateEndpointConnection]:
        """Creates a new Private Endpoint Connection or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param private_endpoint_connection_name: API revision identifier. Must be unique in the current
         API Management service instance. Non-current revision has ;rev=n as a suffix where n is the
         revision number. Required.
        :type private_endpoint_connection_name: str
        :param private_endpoint_connection_request: Is one of the following types:
         PrivateEndpointConnectionRequest, JSON, IO[bytes] Required.
        :type private_endpoint_connection_request:
         ~azure.mgmt.apimanagement.models.PrivateEndpointConnectionRequest or JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns PrivateEndpointConnection. The
         PrivateEndpointConnection is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.PrivateEndpointConnection]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._create_or_update_initial(
                resource_group_name=resource_group_name,
                service_name=service_name,
                private_endpoint_connection_name=private_endpoint_connection_name,
                private_endpoint_connection_request=private_endpoint_connection_request,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.PrivateEndpointConnection, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.PrivateEndpointConnection].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.PrivateEndpointConnection](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _delete_initial(
        self, resource_group_name: str, service_name: str, private_endpoint_connection_name: str, **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        _request = build_private_endpoint_connection_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            private_endpoint_connection_name=private_endpoint_connection_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202, 204]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def begin_delete(
        self, resource_group_name: str, service_name: str, private_endpoint_connection_name: str, **kwargs: Any
    ) -> AsyncLROPoller[None]:
        """Deletes the specified Private Endpoint Connection.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param private_endpoint_connection_name: The name of the private endpoint connection associated
         with the Azure resource. Required.
        :type private_endpoint_connection_name: str
        :return: An instance of AsyncLROPoller that returns None
        :rtype: ~azure.core.polling.AsyncLROPoller[None]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._delete_initial(
                resource_group_name=resource_group_name,
                service_name=service_name,
                private_endpoint_connection_name=private_endpoint_connection_name,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):  # pylint: disable=inconsistent-return-statements
            if cls:
                return cls(pipeline_response, None, {})  # type: ignore

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[None].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method)  # type: ignore

    @distributed_trace
    def list_by_service(
        self, resource_group_name: str, service_name: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.PrivateEndpointConnection"]:
        """Lists all private endpoint connections of the API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :return: An iterator like instance of PrivateEndpointConnection
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.PrivateEndpointConnection]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.PrivateEndpointConnection]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_private_endpoint_connection_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.PrivateEndpointConnection],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def get_private_link_resource(
        self, resource_group_name: str, service_name: str, private_link_sub_resource_name: str, **kwargs: Any
    ) -> _models.PrivateLinkResource:
        """Gets the private link resources.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param private_link_sub_resource_name: The name of the private link associated with the Azure
         resource. Required.
        :type private_link_sub_resource_name: str
        :return: PrivateLinkResource. The PrivateLinkResource is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PrivateLinkResource
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.PrivateLinkResource] = kwargs.pop("cls", None)

        _request = build_private_endpoint_connection_get_private_link_resource_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            private_link_sub_resource_name=private_link_sub_resource_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PrivateLinkResource, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def list_private_link_resources(
        self, resource_group_name: str, service_name: str, **kwargs: Any
    ) -> _models.PrivateLinkResourceListResult:
        """Gets the private link resources.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :return: PrivateLinkResourceListResult. The PrivateLinkResourceListResult is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.PrivateLinkResourceListResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.PrivateLinkResourceListResult] = kwargs.pop("cls", None)

        _request = build_private_endpoint_connection_list_private_link_resources_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PrivateLinkResourceListResult, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class ProductApiOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`product_api` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list_by_product(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.ApiContract"]:
        """Lists a collection of the APIs associated with a product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         displayName | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>| description | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
         endswith |</br>| serviceUrl | filter | ge, le, eq, ne, gt, lt | substringof, contains,
         startswith, endswith |</br>| path | filter | ge, le, eq, ne, gt, lt | substringof, contains,
         startswith, endswith |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of ApiContract
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ApiContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ApiContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_product_api_list_by_product_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    product_id=product_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ApiContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def check_entity_exists(
        self, resource_group_name: str, service_name: str, product_id: str, api_id: str, **kwargs: Any
    ) -> bool:
        """Checks that API entity specified by identifier is associated with the Product entity.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_product_api_check_entity_exists_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            product_id=product_id,
            api_id=api_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore
        return 200 <= response.status_code <= 299

    @distributed_trace_async
    async def create_or_update(
        self, resource_group_name: str, service_name: str, product_id: str, api_id: str, **kwargs: Any
    ) -> _models.ApiContract:
        """Adds an API to the specified product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :return: ApiContract. The ApiContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ApiContract] = kwargs.pop("cls", None)

        _request = build_product_api_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            product_id=product_id,
            api_id=api_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ApiContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self, resource_group_name: str, service_name: str, product_id: str, api_id: str, **kwargs: Any
    ) -> None:
        """Deletes the specified API from the specified product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_product_api_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            product_id=product_id,
            api_id=api_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore


class ProductGroupOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`product_group` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list_by_product(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.GroupContract"]:
        """Lists the collection of developer groups associated with the specified product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt |     |</br>| displayName | filter | eq, ne |     |</br>|
         description | filter | eq, ne |     |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of GroupContract
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.GroupContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.GroupContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_product_group_list_by_product_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    product_id=product_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.GroupContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def check_entity_exists(
        self, resource_group_name: str, service_name: str, product_id: str, group_id: str, **kwargs: Any
    ) -> bool:
        """Checks that Group entity specified by identifier is associated with the Product entity.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param group_id: Group identifier. Must be unique in the current API Management service
         instance. Required.
        :type group_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_product_group_check_entity_exists_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            product_id=product_id,
            group_id=group_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore
        return 200 <= response.status_code <= 299

    @distributed_trace_async
    async def create_or_update(
        self, resource_group_name: str, service_name: str, product_id: str, group_id: str, **kwargs: Any
    ) -> _models.GroupContract:
        """Adds the association between the specified developer group with the specified product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param group_id: Group identifier. Must be unique in the current API Management service
         instance. Required.
        :type group_id: str
        :return: GroupContract. The GroupContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GroupContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.GroupContract] = kwargs.pop("cls", None)

        _request = build_product_group_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            product_id=product_id,
            group_id=group_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.GroupContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self, resource_group_name: str, service_name: str, product_id: str, group_id: str, **kwargs: Any
    ) -> None:
        """Deletes the association between the specified group and product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param group_id: Group identifier. Must be unique in the current API Management service
         instance. Required.
        :type group_id: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_product_group_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            product_id=product_id,
            group_id=group_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore


class ProductSubscriptionsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`product_subscriptions` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.SubscriptionContract"]:
        """Lists the collection of subscriptions to the specified product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         displayName | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>| stateComment | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
         endswith |</br>| ownerId | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
         endswith |</br>| scope | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
         endswith |</br>| userId | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
         endswith |</br>| productId | filter | ge, le, eq, ne, gt, lt | substringof, contains,
         startswith, endswith |</br>| state | filter | eq |     |</br>| user | expand |     |
         |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of SubscriptionContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.SubscriptionContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.SubscriptionContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_product_subscriptions_list_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    product_id=product_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.SubscriptionContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class ProductApiLinkOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`product_api_link` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, product_id: str, api_link_id: str, **kwargs: Any
    ) -> _models.ProductApiLinkContract:
        """Gets the API link for the product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param api_link_id: Product-API link identifier. Must be unique in the current API Management
         service instance. Required.
        :type api_link_id: str
        :return: ProductApiLinkContract. The ProductApiLinkContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductApiLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ProductApiLinkContract] = kwargs.pop("cls", None)

        _request = build_product_api_link_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            product_id=product_id,
            api_link_id=api_link_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ProductApiLinkContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        api_link_id: str,
        parameters: _models.ProductApiLinkContract,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ProductApiLinkContract:
        """Adds an API to the specified product via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param api_link_id: Product-API link identifier. Must be unique in the current API Management
         service instance. Required.
        :type api_link_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ProductApiLinkContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ProductApiLinkContract. The ProductApiLinkContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductApiLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        api_link_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ProductApiLinkContract:
        """Adds an API to the specified product via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param api_link_id: Product-API link identifier. Must be unique in the current API Management
         service instance. Required.
        :type api_link_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ProductApiLinkContract. The ProductApiLinkContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductApiLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        api_link_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ProductApiLinkContract:
        """Adds an API to the specified product via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param api_link_id: Product-API link identifier. Must be unique in the current API Management
         service instance. Required.
        :type api_link_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ProductApiLinkContract. The ProductApiLinkContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductApiLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        api_link_id: str,
        parameters: Union[_models.ProductApiLinkContract, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.ProductApiLinkContract:
        """Adds an API to the specified product via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param api_link_id: Product-API link identifier. Must be unique in the current API Management
         service instance. Required.
        :type api_link_id: str
        :param parameters: Create or update parameters. Is one of the following types:
         ProductApiLinkContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ProductApiLinkContract or JSON or IO[bytes]
        :return: ProductApiLinkContract. The ProductApiLinkContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductApiLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ProductApiLinkContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_product_api_link_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            product_id=product_id,
            api_link_id=api_link_id,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ProductApiLinkContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self, resource_group_name: str, service_name: str, product_id: str, api_link_id: str, **kwargs: Any
    ) -> None:
        """Deletes the specified API from the specified product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param api_link_id: Product-API link identifier. Must be unique in the current API Management
         service instance. Required.
        :type api_link_id: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_product_api_link_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            product_id=product_id,
            api_link_id=api_link_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_product(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.ProductApiLinkContract"]:
        """Lists a collection of the API links associated with a product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| apiId |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of ProductApiLinkContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ProductApiLinkContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ProductApiLinkContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_product_api_link_list_by_product_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    product_id=product_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ProductApiLinkContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class ProductGroupLinkOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`product_group_link` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, product_id: str, group_link_id: str, **kwargs: Any
    ) -> _models.ProductGroupLinkContract:
        """Gets the group link for the product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param group_link_id: Product-Group link identifier. Must be unique in the current API
         Management service instance. Required.
        :type group_link_id: str
        :return: ProductGroupLinkContract. The ProductGroupLinkContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductGroupLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ProductGroupLinkContract] = kwargs.pop("cls", None)

        _request = build_product_group_link_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            product_id=product_id,
            group_link_id=group_link_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ProductGroupLinkContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        group_link_id: str,
        parameters: _models.ProductGroupLinkContract,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ProductGroupLinkContract:
        """Adds a group to the specified product via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param group_link_id: Product-Group link identifier. Must be unique in the current API
         Management service instance. Required.
        :type group_link_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ProductGroupLinkContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ProductGroupLinkContract. The ProductGroupLinkContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductGroupLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        group_link_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ProductGroupLinkContract:
        """Adds a group to the specified product via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param group_link_id: Product-Group link identifier. Must be unique in the current API
         Management service instance. Required.
        :type group_link_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ProductGroupLinkContract. The ProductGroupLinkContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductGroupLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        group_link_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ProductGroupLinkContract:
        """Adds a group to the specified product via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param group_link_id: Product-Group link identifier. Must be unique in the current API
         Management service instance. Required.
        :type group_link_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ProductGroupLinkContract. The ProductGroupLinkContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductGroupLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        group_link_id: str,
        parameters: Union[_models.ProductGroupLinkContract, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.ProductGroupLinkContract:
        """Adds a group to the specified product via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param group_link_id: Product-Group link identifier. Must be unique in the current API
         Management service instance. Required.
        :type group_link_id: str
        :param parameters: Create or update parameters. Is one of the following types:
         ProductGroupLinkContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.ProductGroupLinkContract or JSON or
         IO[bytes]
        :return: ProductGroupLinkContract. The ProductGroupLinkContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ProductGroupLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ProductGroupLinkContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_product_group_link_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            product_id=product_id,
            group_link_id=group_link_id,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ProductGroupLinkContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self, resource_group_name: str, service_name: str, product_id: str, group_link_id: str, **kwargs: Any
    ) -> None:
        """Deletes the specified group from the specified product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :param group_link_id: Product-Group link identifier. Must be unique in the current API
         Management service instance. Required.
        :type group_link_id: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_product_group_link_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            product_id=product_id,
            group_link_id=group_link_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_product(
        self,
        resource_group_name: str,
        service_name: str,
        product_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.ProductGroupLinkContract"]:
        """Lists a collection of the group links associated with a product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param product_id: Product identifier. Must be unique in the current API Management service
         instance. Required.
        :type product_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| groupId |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of ProductGroupLinkContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ProductGroupLinkContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ProductGroupLinkContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_product_group_link_list_by_product_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    product_id=product_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ProductGroupLinkContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class GlobalSchemaOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`global_schema` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, schema_id: str, **kwargs: Any
    ) -> _models.GlobalSchemaContract:
        """Gets the details of the Schema specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param schema_id: Schema id identifier. Must be unique in the current API Management service
         instance. Required.
        :type schema_id: str
        :return: GlobalSchemaContract. The GlobalSchemaContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GlobalSchemaContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.GlobalSchemaContract] = kwargs.pop("cls", None)

        _request = build_global_schema_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            schema_id=schema_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.GlobalSchemaContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(self, resource_group_name: str, service_name: str, schema_id: str, **kwargs: Any) -> bool:
        """Gets the entity state (Etag) version of the Schema specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param schema_id: Schema id identifier. Must be unique in the current API Management service
         instance. Required.
        :type schema_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_global_schema_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            schema_id=schema_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    async def _create_or_update_initial(
        self,
        resource_group_name: str,
        service_name: str,
        schema_id: str,
        parameters: Union[_models.GlobalSchemaContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_global_schema_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            schema_id=schema_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["Azure-AsyncOperation"] = self._deserialize(
            "str", response.headers.get("Azure-AsyncOperation")
        )
        response_headers["location"] = self._deserialize("str", response.headers.get("location"))
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        schema_id: str,
        parameters: _models.GlobalSchemaContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.GlobalSchemaContract]:
        """Creates new or updates existing specified Schema of the API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param schema_id: Schema id identifier. Must be unique in the current API Management service
         instance. Required.
        :type schema_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.GlobalSchemaContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns GlobalSchemaContract. The
         GlobalSchemaContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.GlobalSchemaContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        schema_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.GlobalSchemaContract]:
        """Creates new or updates existing specified Schema of the API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param schema_id: Schema id identifier. Must be unique in the current API Management service
         instance. Required.
        :type schema_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns GlobalSchemaContract. The
         GlobalSchemaContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.GlobalSchemaContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        schema_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.GlobalSchemaContract]:
        """Creates new or updates existing specified Schema of the API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param schema_id: Schema id identifier. Must be unique in the current API Management service
         instance. Required.
        :type schema_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns GlobalSchemaContract. The
         GlobalSchemaContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.GlobalSchemaContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        schema_id: str,
        parameters: Union[_models.GlobalSchemaContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.GlobalSchemaContract]:
        """Creates new or updates existing specified Schema of the API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param schema_id: Schema id identifier. Must be unique in the current API Management service
         instance. Required.
        :type schema_id: str
        :param parameters: Create or update parameters. Is one of the following types:
         GlobalSchemaContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.GlobalSchemaContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: An instance of AsyncLROPoller that returns GlobalSchemaContract. The
         GlobalSchemaContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.GlobalSchemaContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.GlobalSchemaContract] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._create_or_update_initial(
                resource_group_name=resource_group_name,
                service_name=service_name,
                schema_id=schema_id,
                parameters=parameters,
                etag=etag,
                match_condition=match_condition,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response_headers = {}
            response = pipeline_response.http_response
            response_headers["Azure-AsyncOperation"] = self._deserialize(
                "str", response.headers.get("Azure-AsyncOperation")
            )
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

            deserialized = _deserialize(_models.GlobalSchemaContract, response.json())
            if cls:
                return cls(pipeline_response, deserialized, response_headers)  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.GlobalSchemaContract].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.GlobalSchemaContract](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        schema_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes specific Schema.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param schema_id: Schema id identifier. Must be unique in the current API Management service
         instance. Required.
        :type schema_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_global_schema_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            schema_id=schema_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.GlobalSchemaContract"]:
        """Lists a collection of schemas registered with service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of GlobalSchemaContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.GlobalSchemaContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.GlobalSchemaContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_global_schema_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.GlobalSchemaContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class TenantSettingsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`tenant_settings` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self,
        resource_group_name: str,
        service_name: str,
        settings_type: Union[str, _models.SettingsTypeName],
        **kwargs: Any
    ) -> _models.TenantSettingsContract:
        """Get tenant settings.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param settings_type: The identifier of the settings. "public" Required.
        :type settings_type: str or ~azure.mgmt.apimanagement.models.SettingsTypeName
        :return: TenantSettingsContract. The TenantSettingsContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TenantSettingsContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.TenantSettingsContract] = kwargs.pop("cls", None)

        _request = build_tenant_settings_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            settings_type=settings_type,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.TenantSettingsContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list_by_service(
        self, resource_group_name: str, service_name: str, *, filter: Optional[str] = None, **kwargs: Any
    ) -> AsyncItemPaged["_models.TenantSettingsContract"]:
        """Public settings.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: Not used. Default value is None.
        :paramtype filter: str
        :return: An iterator like instance of TenantSettingsContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.TenantSettingsContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.TenantSettingsContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_tenant_settings_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.TenantSettingsContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class SubscriptionOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`subscription` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, sid: str, **kwargs: Any
    ) -> _models.SubscriptionContract:
        """Gets the specified Subscription entity.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param sid: Subscription entity Identifier. The entity represents the association between a
         user and a product in API Management. Required.
        :type sid: str
        :return: SubscriptionContract. The SubscriptionContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.SubscriptionContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.SubscriptionContract] = kwargs.pop("cls", None)

        _request = build_subscription_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            sid=sid,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.SubscriptionContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(self, resource_group_name: str, service_name: str, sid: str, **kwargs: Any) -> bool:
        """Gets the entity state (Etag) version of the apimanagement subscription specified by its
        identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param sid: Subscription entity Identifier. The entity represents the association between a
         user and a product in API Management. Required.
        :type sid: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_subscription_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            sid=sid,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        sid: str,
        parameters: _models.SubscriptionCreateParameters,
        *,
        notify: Optional[bool] = None,
        app_type: Optional[Union[str, _models.AppType]] = None,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.SubscriptionContract:
        """Creates or updates the subscription of specified user to the specified product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param sid: Subscription entity Identifier. The entity represents the association between a
         user and a product in API Management. Required.
        :type sid: str
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.SubscriptionCreateParameters
        :keyword notify: Notify change in Subscription State.

         * If false, do not send any email notification for change of state of subscription
         * If true, send email notification of change of state of subscription. Default value is None.
        :paramtype notify: bool
        :keyword app_type: Determines the type of application which send the create user request.
         Default is legacy publisher portal. Known values are: "portal" and "developerPortal". Default
         value is None.
        :paramtype app_type: str or ~azure.mgmt.apimanagement.models.AppType
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: SubscriptionContract. The SubscriptionContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.SubscriptionContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        sid: str,
        parameters: JSON,
        *,
        notify: Optional[bool] = None,
        app_type: Optional[Union[str, _models.AppType]] = None,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.SubscriptionContract:
        """Creates or updates the subscription of specified user to the specified product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param sid: Subscription entity Identifier. The entity represents the association between a
         user and a product in API Management. Required.
        :type sid: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword notify: Notify change in Subscription State.

         * If false, do not send any email notification for change of state of subscription
         * If true, send email notification of change of state of subscription. Default value is None.
        :paramtype notify: bool
        :keyword app_type: Determines the type of application which send the create user request.
         Default is legacy publisher portal. Known values are: "portal" and "developerPortal". Default
         value is None.
        :paramtype app_type: str or ~azure.mgmt.apimanagement.models.AppType
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: SubscriptionContract. The SubscriptionContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.SubscriptionContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        sid: str,
        parameters: IO[bytes],
        *,
        notify: Optional[bool] = None,
        app_type: Optional[Union[str, _models.AppType]] = None,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.SubscriptionContract:
        """Creates or updates the subscription of specified user to the specified product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param sid: Subscription entity Identifier. The entity represents the association between a
         user and a product in API Management. Required.
        :type sid: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword notify: Notify change in Subscription State.

         * If false, do not send any email notification for change of state of subscription
         * If true, send email notification of change of state of subscription. Default value is None.
        :paramtype notify: bool
        :keyword app_type: Determines the type of application which send the create user request.
         Default is legacy publisher portal. Known values are: "portal" and "developerPortal". Default
         value is None.
        :paramtype app_type: str or ~azure.mgmt.apimanagement.models.AppType
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: SubscriptionContract. The SubscriptionContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.SubscriptionContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        sid: str,
        parameters: Union[_models.SubscriptionCreateParameters, JSON, IO[bytes]],
        *,
        notify: Optional[bool] = None,
        app_type: Optional[Union[str, _models.AppType]] = None,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.SubscriptionContract:
        """Creates or updates the subscription of specified user to the specified product.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param sid: Subscription entity Identifier. The entity represents the association between a
         user and a product in API Management. Required.
        :type sid: str
        :param parameters: Create parameters. Is one of the following types:
         SubscriptionCreateParameters, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.SubscriptionCreateParameters or JSON or
         IO[bytes]
        :keyword notify: Notify change in Subscription State.

         * If false, do not send any email notification for change of state of subscription
         * If true, send email notification of change of state of subscription. Default value is None.
        :paramtype notify: bool
        :keyword app_type: Determines the type of application which send the create user request.
         Default is legacy publisher portal. Known values are: "portal" and "developerPortal". Default
         value is None.
        :paramtype app_type: str or ~azure.mgmt.apimanagement.models.AppType
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: SubscriptionContract. The SubscriptionContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.SubscriptionContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.SubscriptionContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_subscription_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            sid=sid,
            subscription_id=self._config.subscription_id,
            notify=notify,
            app_type=app_type,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.SubscriptionContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        sid: str,
        parameters: _models.SubscriptionUpdateParameters,
        *,
        etag: str,
        match_condition: MatchConditions,
        notify: Optional[bool] = None,
        app_type: Optional[Union[str, _models.AppType]] = None,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.SubscriptionContract:
        """Updates the details of a subscription specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param sid: Subscription entity Identifier. The entity represents the association between a
         user and a product in API Management. Required.
        :type sid: str
        :param parameters: Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.SubscriptionUpdateParameters
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword notify: Notify change in Subscription State.

         * If false, do not send any email notification for change of state of subscription
         * If true, send email notification of change of state of subscription. Default value is None.
        :paramtype notify: bool
        :keyword app_type: Determines the type of application which send the create user request.
         Default is legacy publisher portal. Known values are: "portal" and "developerPortal". Default
         value is None.
        :paramtype app_type: str or ~azure.mgmt.apimanagement.models.AppType
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: SubscriptionContract. The SubscriptionContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.SubscriptionContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        sid: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        notify: Optional[bool] = None,
        app_type: Optional[Union[str, _models.AppType]] = None,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.SubscriptionContract:
        """Updates the details of a subscription specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param sid: Subscription entity Identifier. The entity represents the association between a
         user and a product in API Management. Required.
        :type sid: str
        :param parameters: Update parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword notify: Notify change in Subscription State.

         * If false, do not send any email notification for change of state of subscription
         * If true, send email notification of change of state of subscription. Default value is None.
        :paramtype notify: bool
        :keyword app_type: Determines the type of application which send the create user request.
         Default is legacy publisher portal. Known values are: "portal" and "developerPortal". Default
         value is None.
        :paramtype app_type: str or ~azure.mgmt.apimanagement.models.AppType
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: SubscriptionContract. The SubscriptionContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.SubscriptionContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        sid: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        notify: Optional[bool] = None,
        app_type: Optional[Union[str, _models.AppType]] = None,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.SubscriptionContract:
        """Updates the details of a subscription specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param sid: Subscription entity Identifier. The entity represents the association between a
         user and a product in API Management. Required.
        :type sid: str
        :param parameters: Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword notify: Notify change in Subscription State.

         * If false, do not send any email notification for change of state of subscription
         * If true, send email notification of change of state of subscription. Default value is None.
        :paramtype notify: bool
        :keyword app_type: Determines the type of application which send the create user request.
         Default is legacy publisher portal. Known values are: "portal" and "developerPortal". Default
         value is None.
        :paramtype app_type: str or ~azure.mgmt.apimanagement.models.AppType
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: SubscriptionContract. The SubscriptionContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.SubscriptionContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        sid: str,
        parameters: Union[_models.SubscriptionUpdateParameters, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        notify: Optional[bool] = None,
        app_type: Optional[Union[str, _models.AppType]] = None,
        **kwargs: Any
    ) -> _models.SubscriptionContract:
        """Updates the details of a subscription specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param sid: Subscription entity Identifier. The entity represents the association between a
         user and a product in API Management. Required.
        :type sid: str
        :param parameters: Update parameters. Is one of the following types:
         SubscriptionUpdateParameters, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.SubscriptionUpdateParameters or JSON or
         IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword notify: Notify change in Subscription State.

         * If false, do not send any email notification for change of state of subscription
         * If true, send email notification of change of state of subscription. Default value is None.
        :paramtype notify: bool
        :keyword app_type: Determines the type of application which send the create user request.
         Default is legacy publisher portal. Known values are: "portal" and "developerPortal". Default
         value is None.
        :paramtype app_type: str or ~azure.mgmt.apimanagement.models.AppType
        :return: SubscriptionContract. The SubscriptionContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.SubscriptionContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.SubscriptionContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_subscription_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            sid=sid,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            notify=notify,
            app_type=app_type,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.SubscriptionContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        sid: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes the specified subscription.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param sid: Subscription entity Identifier. The entity represents the association between a
         user and a product in API Management. Required.
        :type sid: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_subscription_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            sid=sid,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.SubscriptionContract"]:
        """Lists all subscriptions of the API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         displayName | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>| stateComment | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
         endswith |</br>| ownerId | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
         endswith |</br>| scope | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
         endswith |</br>| userId | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
         endswith |</br>| productId | filter | ge, le, eq, ne, gt, lt | substringof, contains,
         startswith, endswith |</br>| state | filter | eq |     |</br>| user | expand |     |
         |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of SubscriptionContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.SubscriptionContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.SubscriptionContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_subscription_list_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.SubscriptionContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def regenerate_primary_key(
        self, resource_group_name: str, service_name: str, sid: str, **kwargs: Any
    ) -> None:
        """Regenerates primary key of existing subscription of the API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param sid: Subscription entity Identifier. The entity represents the association between a
         user and a product in API Management. Required.
        :type sid: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_subscription_regenerate_primary_key_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            sid=sid,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace_async
    async def regenerate_secondary_key(
        self, resource_group_name: str, service_name: str, sid: str, **kwargs: Any
    ) -> None:
        """Regenerates secondary key of existing subscription of the API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param sid: Subscription entity Identifier. The entity represents the association between a
         user and a product in API Management. Required.
        :type sid: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_subscription_regenerate_secondary_key_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            sid=sid,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace_async
    async def list_secrets(
        self, resource_group_name: str, service_name: str, sid: str, **kwargs: Any
    ) -> _models.SubscriptionKeysContract:
        """Gets the specified Subscription keys.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param sid: Subscription entity Identifier. The entity represents the association between a
         user and a product in API Management. Required.
        :type sid: str
        :return: SubscriptionKeysContract. The SubscriptionKeysContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.SubscriptionKeysContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.SubscriptionKeysContract] = kwargs.pop("cls", None)

        _request = build_subscription_list_secrets_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            sid=sid,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.SubscriptionKeysContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore


class TagApiLinkOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`tag_api_link` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, tag_id: str, api_link_id: str, **kwargs: Any
    ) -> _models.TagApiLinkContract:
        """Gets the API link for the tag.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param api_link_id: Tag-API link identifier. Must be unique in the current API Management
         service instance. Required.
        :type api_link_id: str
        :return: TagApiLinkContract. The TagApiLinkContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagApiLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.TagApiLinkContract] = kwargs.pop("cls", None)

        _request = build_tag_api_link_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            tag_id=tag_id,
            api_link_id=api_link_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.TagApiLinkContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        tag_id: str,
        api_link_id: str,
        parameters: _models.TagApiLinkContract,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.TagApiLinkContract:
        """Adds an API to the specified tag via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param api_link_id: Tag-API link identifier. Must be unique in the current API Management
         service instance. Required.
        :type api_link_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.TagApiLinkContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: TagApiLinkContract. The TagApiLinkContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagApiLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        tag_id: str,
        api_link_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.TagApiLinkContract:
        """Adds an API to the specified tag via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param api_link_id: Tag-API link identifier. Must be unique in the current API Management
         service instance. Required.
        :type api_link_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: TagApiLinkContract. The TagApiLinkContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagApiLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        tag_id: str,
        api_link_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.TagApiLinkContract:
        """Adds an API to the specified tag via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param api_link_id: Tag-API link identifier. Must be unique in the current API Management
         service instance. Required.
        :type api_link_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: TagApiLinkContract. The TagApiLinkContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagApiLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        tag_id: str,
        api_link_id: str,
        parameters: Union[_models.TagApiLinkContract, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.TagApiLinkContract:
        """Adds an API to the specified tag via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param api_link_id: Tag-API link identifier. Must be unique in the current API Management
         service instance. Required.
        :type api_link_id: str
        :param parameters: Create or update parameters. Is one of the following types:
         TagApiLinkContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.TagApiLinkContract or JSON or IO[bytes]
        :return: TagApiLinkContract. The TagApiLinkContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagApiLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.TagApiLinkContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_tag_api_link_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            tag_id=tag_id,
            api_link_id=api_link_id,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.TagApiLinkContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self, resource_group_name: str, service_name: str, tag_id: str, api_link_id: str, **kwargs: Any
    ) -> None:
        """Deletes the specified API from the specified tag.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param api_link_id: Tag-API link identifier. Must be unique in the current API Management
         service instance. Required.
        :type api_link_id: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_tag_api_link_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            tag_id=tag_id,
            api_link_id=api_link_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_product(
        self,
        resource_group_name: str,
        service_name: str,
        tag_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.TagApiLinkContract"]:
        """Lists a collection of the API links associated with a tag.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| apiId |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of TagApiLinkContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.TagApiLinkContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.TagApiLinkContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_tag_api_link_list_by_product_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    tag_id=tag_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.TagApiLinkContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class TagOperationLinkOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`tag_operation_link` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, tag_id: str, operation_link_id: str, **kwargs: Any
    ) -> _models.TagOperationLinkContract:
        """Gets the operation link for the tag.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param operation_link_id: Tag-operation link identifier. Must be unique in the current API
         Management service instance. Required.
        :type operation_link_id: str
        :return: TagOperationLinkContract. The TagOperationLinkContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagOperationLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.TagOperationLinkContract] = kwargs.pop("cls", None)

        _request = build_tag_operation_link_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            tag_id=tag_id,
            operation_link_id=operation_link_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.TagOperationLinkContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        tag_id: str,
        operation_link_id: str,
        parameters: _models.TagOperationLinkContract,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.TagOperationLinkContract:
        """Adds an operation to the specified tag via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param operation_link_id: Tag-operation link identifier. Must be unique in the current API
         Management service instance. Required.
        :type operation_link_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.TagOperationLinkContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: TagOperationLinkContract. The TagOperationLinkContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagOperationLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        tag_id: str,
        operation_link_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.TagOperationLinkContract:
        """Adds an operation to the specified tag via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param operation_link_id: Tag-operation link identifier. Must be unique in the current API
         Management service instance. Required.
        :type operation_link_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: TagOperationLinkContract. The TagOperationLinkContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagOperationLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        tag_id: str,
        operation_link_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.TagOperationLinkContract:
        """Adds an operation to the specified tag via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param operation_link_id: Tag-operation link identifier. Must be unique in the current API
         Management service instance. Required.
        :type operation_link_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: TagOperationLinkContract. The TagOperationLinkContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagOperationLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        tag_id: str,
        operation_link_id: str,
        parameters: Union[_models.TagOperationLinkContract, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.TagOperationLinkContract:
        """Adds an operation to the specified tag via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param operation_link_id: Tag-operation link identifier. Must be unique in the current API
         Management service instance. Required.
        :type operation_link_id: str
        :param parameters: Create or update parameters. Is one of the following types:
         TagOperationLinkContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.TagOperationLinkContract or JSON or
         IO[bytes]
        :return: TagOperationLinkContract. The TagOperationLinkContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagOperationLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.TagOperationLinkContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_tag_operation_link_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            tag_id=tag_id,
            operation_link_id=operation_link_id,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.TagOperationLinkContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self, resource_group_name: str, service_name: str, tag_id: str, operation_link_id: str, **kwargs: Any
    ) -> None:
        """Deletes the specified operation from the specified tag.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param operation_link_id: Tag-operation link identifier. Must be unique in the current API
         Management service instance. Required.
        :type operation_link_id: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_tag_operation_link_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            tag_id=tag_id,
            operation_link_id=operation_link_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_product(
        self,
        resource_group_name: str,
        service_name: str,
        tag_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.TagOperationLinkContract"]:
        """Lists a collection of the operation links associated with a tag.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| operationId
         | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of TagOperationLinkContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.TagOperationLinkContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.TagOperationLinkContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_tag_operation_link_list_by_product_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    tag_id=tag_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.TagOperationLinkContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class TagProductLinkOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`tag_product_link` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, tag_id: str, product_link_id: str, **kwargs: Any
    ) -> _models.TagProductLinkContract:
        """Gets the product link for the tag.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param product_link_id: Tag-product link identifier. Must be unique in the current API
         Management service instance. Required.
        :type product_link_id: str
        :return: TagProductLinkContract. The TagProductLinkContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagProductLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.TagProductLinkContract] = kwargs.pop("cls", None)

        _request = build_tag_product_link_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            tag_id=tag_id,
            product_link_id=product_link_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.TagProductLinkContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        tag_id: str,
        product_link_id: str,
        parameters: _models.TagProductLinkContract,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.TagProductLinkContract:
        """Adds a product to the specified tag via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param product_link_id: Tag-product link identifier. Must be unique in the current API
         Management service instance. Required.
        :type product_link_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.TagProductLinkContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: TagProductLinkContract. The TagProductLinkContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagProductLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        tag_id: str,
        product_link_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.TagProductLinkContract:
        """Adds a product to the specified tag via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param product_link_id: Tag-product link identifier. Must be unique in the current API
         Management service instance. Required.
        :type product_link_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: TagProductLinkContract. The TagProductLinkContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagProductLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        tag_id: str,
        product_link_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.TagProductLinkContract:
        """Adds a product to the specified tag via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param product_link_id: Tag-product link identifier. Must be unique in the current API
         Management service instance. Required.
        :type product_link_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: TagProductLinkContract. The TagProductLinkContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagProductLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        tag_id: str,
        product_link_id: str,
        parameters: Union[_models.TagProductLinkContract, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.TagProductLinkContract:
        """Adds a product to the specified tag via link.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param product_link_id: Tag-product link identifier. Must be unique in the current API
         Management service instance. Required.
        :type product_link_id: str
        :param parameters: Create or update parameters. Is one of the following types:
         TagProductLinkContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.TagProductLinkContract or JSON or IO[bytes]
        :return: TagProductLinkContract. The TagProductLinkContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TagProductLinkContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.TagProductLinkContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_tag_product_link_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            tag_id=tag_id,
            product_link_id=product_link_id,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.TagProductLinkContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self, resource_group_name: str, service_name: str, tag_id: str, product_link_id: str, **kwargs: Any
    ) -> None:
        """Deletes the specified product from the specified tag.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :param product_link_id: Tag-product link identifier. Must be unique in the current API
         Management service instance. Required.
        :type product_link_id: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_tag_product_link_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            tag_id=tag_id,
            product_link_id=product_link_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_product(
        self,
        resource_group_name: str,
        service_name: str,
        tag_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.TagProductLinkContract"]:
        """Lists a collection of the product links associated with a tag.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param tag_id: Tag identifier. Must be unique in the current API Management service instance.
         Required.
        :type tag_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| productId |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>. Default
         value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of TagProductLinkContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.TagProductLinkContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.TagProductLinkContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_tag_product_link_list_by_product_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    tag_id=tag_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.TagProductLinkContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class TenantAccessOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`tenant_access` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, access_name: Union[str, _models.AccessIdName], **kwargs: Any
    ) -> _models.AccessInformationContract:
        """Get tenant access information details without secrets.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param access_name: The identifier of the Access configuration. Known values are: "access" and
         "gitAccess". Required.
        :type access_name: str or ~azure.mgmt.apimanagement.models.AccessIdName
        :return: AccessInformationContract. The AccessInformationContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AccessInformationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.AccessInformationContract] = kwargs.pop("cls", None)

        _request = build_tenant_access_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            access_name=access_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.AccessInformationContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, access_name: Union[str, _models.AccessIdName], **kwargs: Any
    ) -> bool:
        """Tenant access metadata.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param access_name: The identifier of the Access configuration. Known values are: "access" and
         "gitAccess". Required.
        :type access_name: str or ~azure.mgmt.apimanagement.models.AccessIdName
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_tenant_access_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            access_name=access_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create(
        self,
        resource_group_name: str,
        service_name: str,
        access_name: Union[str, _models.AccessIdName],
        parameters: _models.AccessInformationCreateParameters,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.AccessInformationContract:
        """Update tenant access information details.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param access_name: The identifier of the Access configuration. Known values are: "access" and
         "gitAccess". Required.
        :type access_name: str or ~azure.mgmt.apimanagement.models.AccessIdName
        :param parameters: Parameters supplied to retrieve the Tenant Access Information. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.AccessInformationCreateParameters
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: AccessInformationContract. The AccessInformationContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AccessInformationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create(
        self,
        resource_group_name: str,
        service_name: str,
        access_name: Union[str, _models.AccessIdName],
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.AccessInformationContract:
        """Update tenant access information details.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param access_name: The identifier of the Access configuration. Known values are: "access" and
         "gitAccess". Required.
        :type access_name: str or ~azure.mgmt.apimanagement.models.AccessIdName
        :param parameters: Parameters supplied to retrieve the Tenant Access Information. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: AccessInformationContract. The AccessInformationContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AccessInformationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create(
        self,
        resource_group_name: str,
        service_name: str,
        access_name: Union[str, _models.AccessIdName],
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.AccessInformationContract:
        """Update tenant access information details.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param access_name: The identifier of the Access configuration. Known values are: "access" and
         "gitAccess". Required.
        :type access_name: str or ~azure.mgmt.apimanagement.models.AccessIdName
        :param parameters: Parameters supplied to retrieve the Tenant Access Information. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: AccessInformationContract. The AccessInformationContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AccessInformationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create(
        self,
        resource_group_name: str,
        service_name: str,
        access_name: Union[str, _models.AccessIdName],
        parameters: Union[_models.AccessInformationCreateParameters, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.AccessInformationContract:
        """Update tenant access information details.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param access_name: The identifier of the Access configuration. Known values are: "access" and
         "gitAccess". Required.
        :type access_name: str or ~azure.mgmt.apimanagement.models.AccessIdName
        :param parameters: Parameters supplied to retrieve the Tenant Access Information. Is one of the
         following types: AccessInformationCreateParameters, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.AccessInformationCreateParameters or JSON or
         IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: AccessInformationContract. The AccessInformationContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AccessInformationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.AccessInformationContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_tenant_access_create_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            access_name=access_name,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.AccessInformationContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        access_name: Union[str, _models.AccessIdName],
        parameters: _models.AccessInformationUpdateParameters,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.AccessInformationContract:
        """Update tenant access information details.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param access_name: The identifier of the Access configuration. Known values are: "access" and
         "gitAccess". Required.
        :type access_name: str or ~azure.mgmt.apimanagement.models.AccessIdName
        :param parameters: Parameters supplied to retrieve the Tenant Access Information. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.AccessInformationUpdateParameters
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: AccessInformationContract. The AccessInformationContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AccessInformationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        access_name: Union[str, _models.AccessIdName],
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.AccessInformationContract:
        """Update tenant access information details.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param access_name: The identifier of the Access configuration. Known values are: "access" and
         "gitAccess". Required.
        :type access_name: str or ~azure.mgmt.apimanagement.models.AccessIdName
        :param parameters: Parameters supplied to retrieve the Tenant Access Information. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: AccessInformationContract. The AccessInformationContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AccessInformationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        access_name: Union[str, _models.AccessIdName],
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.AccessInformationContract:
        """Update tenant access information details.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param access_name: The identifier of the Access configuration. Known values are: "access" and
         "gitAccess". Required.
        :type access_name: str or ~azure.mgmt.apimanagement.models.AccessIdName
        :param parameters: Parameters supplied to retrieve the Tenant Access Information. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: AccessInformationContract. The AccessInformationContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AccessInformationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        access_name: Union[str, _models.AccessIdName],
        parameters: Union[_models.AccessInformationUpdateParameters, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.AccessInformationContract:
        """Update tenant access information details.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param access_name: The identifier of the Access configuration. Known values are: "access" and
         "gitAccess". Required.
        :type access_name: str or ~azure.mgmt.apimanagement.models.AccessIdName
        :param parameters: Parameters supplied to retrieve the Tenant Access Information. Is one of the
         following types: AccessInformationUpdateParameters, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.AccessInformationUpdateParameters or JSON or
         IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: AccessInformationContract. The AccessInformationContract is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AccessInformationContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.AccessInformationContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_tenant_access_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            access_name=access_name,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.AccessInformationContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list_by_service(
        self, resource_group_name: str, service_name: str, *, filter: Optional[str] = None, **kwargs: Any
    ) -> AsyncItemPaged["_models.AccessInformationContract"]:
        """Returns list of access infos - for Git and Management endpoints.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: Not used. Default value is None.
        :paramtype filter: str
        :return: An iterator like instance of AccessInformationContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.AccessInformationContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.AccessInformationContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_tenant_access_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.AccessInformationContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def regenerate_primary_key(
        self, resource_group_name: str, service_name: str, access_name: Union[str, _models.AccessIdName], **kwargs: Any
    ) -> None:
        """Regenerate primary access key.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param access_name: The identifier of the Access configuration. Known values are: "access" and
         "gitAccess". Required.
        :type access_name: str or ~azure.mgmt.apimanagement.models.AccessIdName
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_tenant_access_regenerate_primary_key_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            access_name=access_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace_async
    async def regenerate_secondary_key(
        self, resource_group_name: str, service_name: str, access_name: Union[str, _models.AccessIdName], **kwargs: Any
    ) -> None:
        """Regenerate secondary access key.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param access_name: The identifier of the Access configuration. Known values are: "access" and
         "gitAccess". Required.
        :type access_name: str or ~azure.mgmt.apimanagement.models.AccessIdName
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_tenant_access_regenerate_secondary_key_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            access_name=access_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace_async
    async def list_secrets(
        self, resource_group_name: str, service_name: str, access_name: Union[str, _models.AccessIdName], **kwargs: Any
    ) -> _models.AccessInformationSecretsContract:
        """Get tenant access information details.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param access_name: The identifier of the Access configuration. Known values are: "access" and
         "gitAccess". Required.
        :type access_name: str or ~azure.mgmt.apimanagement.models.AccessIdName
        :return: AccessInformationSecretsContract. The AccessInformationSecretsContract is compatible
         with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.AccessInformationSecretsContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.AccessInformationSecretsContract] = kwargs.pop("cls", None)

        _request = build_tenant_access_list_secrets_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            access_name=access_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.AccessInformationSecretsContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore


class TenantAccessGitOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`tenant_access_git` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def regenerate_primary_key(
        self, resource_group_name: str, service_name: str, access_name: Union[str, _models.AccessIdName], **kwargs: Any
    ) -> None:
        """Regenerate primary access key for GIT.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param access_name: The identifier of the Access configuration. Known values are: "access" and
         "gitAccess". Required.
        :type access_name: str or ~azure.mgmt.apimanagement.models.AccessIdName
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_tenant_access_git_regenerate_primary_key_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            access_name=access_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace_async
    async def regenerate_secondary_key(
        self, resource_group_name: str, service_name: str, access_name: Union[str, _models.AccessIdName], **kwargs: Any
    ) -> None:
        """Regenerate secondary access key for GIT.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param access_name: The identifier of the Access configuration. Known values are: "access" and
         "gitAccess". Required.
        :type access_name: str or ~azure.mgmt.apimanagement.models.AccessIdName
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_tenant_access_git_regenerate_secondary_key_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            access_name=access_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore


class TenantConfigurationOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`tenant_configuration` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    async def _deploy_initial(
        self,
        resource_group_name: str,
        service_name: str,
        configuration_name: Union[str, _models.ConfigurationIdName],
        parameters: Union[_models.DeployConfigurationParameters, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_tenant_configuration_deploy_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            configuration_name=configuration_name,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_deploy(
        self,
        resource_group_name: str,
        service_name: str,
        configuration_name: Union[str, _models.ConfigurationIdName],
        parameters: _models.DeployConfigurationParameters,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.OperationResultContract]:
        """This operation applies changes from the specified Git branch to the configuration database.
        This is a long running operation and could take several minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param configuration_name: API revision identifier. Must be unique in the current API
         Management service instance. Non-current revision has ;rev=n as a suffix where n is the
         revision number. "configuration" Required.
        :type configuration_name: str or ~azure.mgmt.apimanagement.models.ConfigurationIdName
        :param parameters: Deploy Configuration parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.DeployConfigurationParameters
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns OperationResultContract. The
         OperationResultContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.OperationResultContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_deploy(
        self,
        resource_group_name: str,
        service_name: str,
        configuration_name: Union[str, _models.ConfigurationIdName],
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.OperationResultContract]:
        """This operation applies changes from the specified Git branch to the configuration database.
        This is a long running operation and could take several minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param configuration_name: API revision identifier. Must be unique in the current API
         Management service instance. Non-current revision has ;rev=n as a suffix where n is the
         revision number. "configuration" Required.
        :type configuration_name: str or ~azure.mgmt.apimanagement.models.ConfigurationIdName
        :param parameters: Deploy Configuration parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns OperationResultContract. The
         OperationResultContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.OperationResultContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_deploy(
        self,
        resource_group_name: str,
        service_name: str,
        configuration_name: Union[str, _models.ConfigurationIdName],
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.OperationResultContract]:
        """This operation applies changes from the specified Git branch to the configuration database.
        This is a long running operation and could take several minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param configuration_name: API revision identifier. Must be unique in the current API
         Management service instance. Non-current revision has ;rev=n as a suffix where n is the
         revision number. "configuration" Required.
        :type configuration_name: str or ~azure.mgmt.apimanagement.models.ConfigurationIdName
        :param parameters: Deploy Configuration parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns OperationResultContract. The
         OperationResultContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.OperationResultContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_deploy(
        self,
        resource_group_name: str,
        service_name: str,
        configuration_name: Union[str, _models.ConfigurationIdName],
        parameters: Union[_models.DeployConfigurationParameters, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.OperationResultContract]:
        """This operation applies changes from the specified Git branch to the configuration database.
        This is a long running operation and could take several minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param configuration_name: API revision identifier. Must be unique in the current API
         Management service instance. Non-current revision has ;rev=n as a suffix where n is the
         revision number. "configuration" Required.
        :type configuration_name: str or ~azure.mgmt.apimanagement.models.ConfigurationIdName
        :param parameters: Deploy Configuration parameters. Is one of the following types:
         DeployConfigurationParameters, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.DeployConfigurationParameters or JSON or
         IO[bytes]
        :return: An instance of AsyncLROPoller that returns OperationResultContract. The
         OperationResultContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.OperationResultContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.OperationResultContract] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._deploy_initial(
                resource_group_name=resource_group_name,
                service_name=service_name,
                configuration_name=configuration_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.OperationResultContract, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.OperationResultContract].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.OperationResultContract](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _save_initial(
        self,
        resource_group_name: str,
        service_name: str,
        configuration_name: Union[str, _models.ConfigurationIdName],
        parameters: Union[_models.SaveConfigurationParameter, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_tenant_configuration_save_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            configuration_name=configuration_name,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_save(
        self,
        resource_group_name: str,
        service_name: str,
        configuration_name: Union[str, _models.ConfigurationIdName],
        parameters: _models.SaveConfigurationParameter,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.OperationResultContract]:
        """This operation creates a commit with the current configuration snapshot to the specified branch
        in the repository. This is a long running operation and could take several minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param configuration_name: API revision identifier. Must be unique in the current API
         Management service instance. Non-current revision has ;rev=n as a suffix where n is the
         revision number. "configuration" Required.
        :type configuration_name: str or ~azure.mgmt.apimanagement.models.ConfigurationIdName
        :param parameters: Save Configuration parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.SaveConfigurationParameter
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns OperationResultContract. The
         OperationResultContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.OperationResultContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_save(
        self,
        resource_group_name: str,
        service_name: str,
        configuration_name: Union[str, _models.ConfigurationIdName],
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.OperationResultContract]:
        """This operation creates a commit with the current configuration snapshot to the specified branch
        in the repository. This is a long running operation and could take several minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param configuration_name: API revision identifier. Must be unique in the current API
         Management service instance. Non-current revision has ;rev=n as a suffix where n is the
         revision number. "configuration" Required.
        :type configuration_name: str or ~azure.mgmt.apimanagement.models.ConfigurationIdName
        :param parameters: Save Configuration parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns OperationResultContract. The
         OperationResultContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.OperationResultContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_save(
        self,
        resource_group_name: str,
        service_name: str,
        configuration_name: Union[str, _models.ConfigurationIdName],
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.OperationResultContract]:
        """This operation creates a commit with the current configuration snapshot to the specified branch
        in the repository. This is a long running operation and could take several minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param configuration_name: API revision identifier. Must be unique in the current API
         Management service instance. Non-current revision has ;rev=n as a suffix where n is the
         revision number. "configuration" Required.
        :type configuration_name: str or ~azure.mgmt.apimanagement.models.ConfigurationIdName
        :param parameters: Save Configuration parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns OperationResultContract. The
         OperationResultContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.OperationResultContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_save(
        self,
        resource_group_name: str,
        service_name: str,
        configuration_name: Union[str, _models.ConfigurationIdName],
        parameters: Union[_models.SaveConfigurationParameter, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.OperationResultContract]:
        """This operation creates a commit with the current configuration snapshot to the specified branch
        in the repository. This is a long running operation and could take several minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param configuration_name: API revision identifier. Must be unique in the current API
         Management service instance. Non-current revision has ;rev=n as a suffix where n is the
         revision number. "configuration" Required.
        :type configuration_name: str or ~azure.mgmt.apimanagement.models.ConfigurationIdName
        :param parameters: Save Configuration parameters. Is one of the following types:
         SaveConfigurationParameter, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.SaveConfigurationParameter or JSON or
         IO[bytes]
        :return: An instance of AsyncLROPoller that returns OperationResultContract. The
         OperationResultContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.OperationResultContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.OperationResultContract] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._save_initial(
                resource_group_name=resource_group_name,
                service_name=service_name,
                configuration_name=configuration_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.OperationResultContract, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.OperationResultContract].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.OperationResultContract](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _validate_initial(
        self,
        resource_group_name: str,
        service_name: str,
        configuration_name: Union[str, _models.ConfigurationIdName],
        parameters: Union[_models.DeployConfigurationParameters, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_tenant_configuration_validate_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            configuration_name=configuration_name,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_validate(
        self,
        resource_group_name: str,
        service_name: str,
        configuration_name: Union[str, _models.ConfigurationIdName],
        parameters: _models.DeployConfigurationParameters,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.OperationResultContract]:
        """This operation validates the changes in the specified Git branch. This is a long running
        operation and could take several minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param configuration_name: API revision identifier. Must be unique in the current API
         Management service instance. Non-current revision has ;rev=n as a suffix where n is the
         revision number. "configuration" Required.
        :type configuration_name: str or ~azure.mgmt.apimanagement.models.ConfigurationIdName
        :param parameters: Validate Configuration parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.DeployConfigurationParameters
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns OperationResultContract. The
         OperationResultContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.OperationResultContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_validate(
        self,
        resource_group_name: str,
        service_name: str,
        configuration_name: Union[str, _models.ConfigurationIdName],
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.OperationResultContract]:
        """This operation validates the changes in the specified Git branch. This is a long running
        operation and could take several minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param configuration_name: API revision identifier. Must be unique in the current API
         Management service instance. Non-current revision has ;rev=n as a suffix where n is the
         revision number. "configuration" Required.
        :type configuration_name: str or ~azure.mgmt.apimanagement.models.ConfigurationIdName
        :param parameters: Validate Configuration parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns OperationResultContract. The
         OperationResultContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.OperationResultContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_validate(
        self,
        resource_group_name: str,
        service_name: str,
        configuration_name: Union[str, _models.ConfigurationIdName],
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.OperationResultContract]:
        """This operation validates the changes in the specified Git branch. This is a long running
        operation and could take several minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param configuration_name: API revision identifier. Must be unique in the current API
         Management service instance. Non-current revision has ;rev=n as a suffix where n is the
         revision number. "configuration" Required.
        :type configuration_name: str or ~azure.mgmt.apimanagement.models.ConfigurationIdName
        :param parameters: Validate Configuration parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns OperationResultContract. The
         OperationResultContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.OperationResultContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_validate(
        self,
        resource_group_name: str,
        service_name: str,
        configuration_name: Union[str, _models.ConfigurationIdName],
        parameters: Union[_models.DeployConfigurationParameters, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.OperationResultContract]:
        """This operation validates the changes in the specified Git branch. This is a long running
        operation and could take several minutes to complete.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param configuration_name: API revision identifier. Must be unique in the current API
         Management service instance. Non-current revision has ;rev=n as a suffix where n is the
         revision number. "configuration" Required.
        :type configuration_name: str or ~azure.mgmt.apimanagement.models.ConfigurationIdName
        :param parameters: Validate Configuration parameters. Is one of the following types:
         DeployConfigurationParameters, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.DeployConfigurationParameters or JSON or
         IO[bytes]
        :return: An instance of AsyncLROPoller that returns OperationResultContract. The
         OperationResultContract is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.OperationResultContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.OperationResultContract] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._validate_initial(
                resource_group_name=resource_group_name,
                service_name=service_name,
                configuration_name=configuration_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.OperationResultContract, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.OperationResultContract].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.OperationResultContract](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @distributed_trace_async
    async def get_sync_state(
        self,
        resource_group_name: str,
        service_name: str,
        configuration_name: Union[str, _models.ConfigurationIdName],
        **kwargs: Any
    ) -> _models.TenantConfigurationSyncStateContract:
        """Gets the status of the most recent synchronization between the configuration database and the
        Git repository.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param configuration_name: API revision identifier. Must be unique in the current API
         Management service instance. Non-current revision has ;rev=n as a suffix where n is the
         revision number. "configuration" Required.
        :type configuration_name: str or ~azure.mgmt.apimanagement.models.ConfigurationIdName
        :return: TenantConfigurationSyncStateContract. The TenantConfigurationSyncStateContract is
         compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.TenantConfigurationSyncStateContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.TenantConfigurationSyncStateContract] = kwargs.pop("cls", None)

        _request = build_tenant_configuration_get_sync_state_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            configuration_name=configuration_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.TenantConfigurationSyncStateContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class UserOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`user` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, user_id: str, **kwargs: Any
    ) -> _models.UserContract:
        """Gets the details of the user specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param user_id: User identifier. Must be unique in the current API Management service instance.
         Required.
        :type user_id: str
        :return: UserContract. The UserContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.UserContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.UserContract] = kwargs.pop("cls", None)

        _request = build_user_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            user_id=user_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.UserContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(self, resource_group_name: str, service_name: str, user_id: str, **kwargs: Any) -> bool:
        """Gets the entity state (Etag) version of the user specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param user_id: User identifier. Must be unique in the current API Management service instance.
         Required.
        :type user_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_user_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            user_id=user_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        user_id: str,
        parameters: _models.UserCreateParameters,
        *,
        notify: Optional[bool] = None,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.UserContract:
        """Creates or Updates a user.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param user_id: User identifier. Must be unique in the current API Management service instance.
         Required.
        :type user_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.UserCreateParameters
        :keyword notify: Send an Email notification to the User. Default value is None.
        :paramtype notify: bool
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: UserContract. The UserContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.UserContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        user_id: str,
        parameters: JSON,
        *,
        notify: Optional[bool] = None,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.UserContract:
        """Creates or Updates a user.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param user_id: User identifier. Must be unique in the current API Management service instance.
         Required.
        :type user_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: JSON
        :keyword notify: Send an Email notification to the User. Default value is None.
        :paramtype notify: bool
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: UserContract. The UserContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.UserContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        user_id: str,
        parameters: IO[bytes],
        *,
        notify: Optional[bool] = None,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.UserContract:
        """Creates or Updates a user.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param user_id: User identifier. Must be unique in the current API Management service instance.
         Required.
        :type user_id: str
        :param parameters: Create or update parameters. Required.
        :type parameters: IO[bytes]
        :keyword notify: Send an Email notification to the User. Default value is None.
        :paramtype notify: bool
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: UserContract. The UserContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.UserContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        user_id: str,
        parameters: Union[_models.UserCreateParameters, JSON, IO[bytes]],
        *,
        notify: Optional[bool] = None,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.UserContract:
        """Creates or Updates a user.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param user_id: User identifier. Must be unique in the current API Management service instance.
         Required.
        :type user_id: str
        :param parameters: Create or update parameters. Is one of the following types:
         UserCreateParameters, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.UserCreateParameters or JSON or IO[bytes]
        :keyword notify: Send an Email notification to the User. Default value is None.
        :paramtype notify: bool
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: UserContract. The UserContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.UserContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.UserContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_user_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            user_id=user_id,
            subscription_id=self._config.subscription_id,
            notify=notify,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 200:
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if response.status_code == 201:
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))
            response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.UserContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        user_id: str,
        parameters: _models.UserUpdateParameters,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.UserContract:
        """Updates the details of the user specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param user_id: User identifier. Must be unique in the current API Management service instance.
         Required.
        :type user_id: str
        :param parameters: Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.UserUpdateParameters
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: UserContract. The UserContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.UserContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        user_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.UserContract:
        """Updates the details of the user specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param user_id: User identifier. Must be unique in the current API Management service instance.
         Required.
        :type user_id: str
        :param parameters: Update parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: UserContract. The UserContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.UserContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        user_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.UserContract:
        """Updates the details of the user specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param user_id: User identifier. Must be unique in the current API Management service instance.
         Required.
        :type user_id: str
        :param parameters: Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: UserContract. The UserContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.UserContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        user_id: str,
        parameters: Union[_models.UserUpdateParameters, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.UserContract:
        """Updates the details of the user specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param user_id: User identifier. Must be unique in the current API Management service instance.
         Required.
        :type user_id: str
        :param parameters: Update parameters. Is one of the following types: UserUpdateParameters,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.UserUpdateParameters or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: UserContract. The UserContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.UserContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.UserContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_user_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            user_id=user_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.UserContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    async def _delete_initial(
        self,
        resource_group_name: str,
        service_name: str,
        user_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        delete_subscriptions: Optional[bool] = None,
        notify: Optional[bool] = None,
        app_type: Optional[Union[str, _models.AppType]] = None,
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        _request = build_user_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            user_id=user_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            delete_subscriptions=delete_subscriptions,
            notify=notify,
            app_type=app_type,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [202, 204]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Azure-AsyncOperation"] = self._deserialize(
                "str", response.headers.get("Azure-AsyncOperation")
            )
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def begin_delete(
        self,
        resource_group_name: str,
        service_name: str,
        user_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        delete_subscriptions: Optional[bool] = None,
        notify: Optional[bool] = None,
        app_type: Optional[Union[str, _models.AppType]] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[None]:
        """Deletes specific user.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param user_id: User identifier. Must be unique in the current API Management service instance.
         Required.
        :type user_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword delete_subscriptions: Whether to delete user's subscription or not. Default value is
         None.
        :paramtype delete_subscriptions: bool
        :keyword notify: Send an Account Closed Email notification to the User. Default value is None.
        :paramtype notify: bool
        :keyword app_type: Determines the type of application which send the create user request.
         Default is legacy publisher portal. Known values are: "portal" and "developerPortal". Default
         value is None.
        :paramtype app_type: str or ~azure.mgmt.apimanagement.models.AppType
        :return: An instance of AsyncLROPoller that returns None
        :rtype: ~azure.core.polling.AsyncLROPoller[None]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._delete_initial(
                resource_group_name=resource_group_name,
                service_name=service_name,
                user_id=user_id,
                etag=etag,
                match_condition=match_condition,
                delete_subscriptions=delete_subscriptions,
                notify=notify,
                app_type=app_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):  # pylint: disable=inconsistent-return-statements
            if cls:
                return cls(pipeline_response, None, {})  # type: ignore

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[None].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method)  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        expand_groups: Optional[bool] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.UserContract"]:
        """Lists a collection of registered users in the specified service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>| firstName
         | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         lastName | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>| email | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>| state | filter | eq |     |</br>| registrationDate | filter | ge, le, eq, ne, gt, lt |
         |</br>| note | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>| groups | expand |     |     |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :keyword expand_groups: Detailed Group in response. Default value is None.
        :paramtype expand_groups: bool
        :return: An iterator like instance of UserContract
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.UserContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.UserContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_user_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    expand_groups=expand_groups,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.UserContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def generate_sso_url(
        self, resource_group_name: str, service_name: str, user_id: str, **kwargs: Any
    ) -> _models.GenerateSsoUrlResult:
        """Retrieves a redirection URL containing an authentication token for signing a given user into
        the developer portal.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param user_id: User identifier. Must be unique in the current API Management service instance.
         Required.
        :type user_id: str
        :return: GenerateSsoUrlResult. The GenerateSsoUrlResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.GenerateSsoUrlResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.GenerateSsoUrlResult] = kwargs.pop("cls", None)

        _request = build_user_generate_sso_url_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            user_id=user_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.GenerateSsoUrlResult, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def get_shared_access_token(
        self,
        resource_group_name: str,
        service_name: str,
        user_id: str,
        parameters: _models.UserTokenParameters,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.UserTokenResult:
        """Gets the Shared Access Authorization Token for the User.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param user_id: User identifier. Must be unique in the current API Management service instance.
         Required.
        :type user_id: str
        :param parameters: Create Authorization Token parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.UserTokenParameters
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: UserTokenResult. The UserTokenResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.UserTokenResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def get_shared_access_token(
        self,
        resource_group_name: str,
        service_name: str,
        user_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.UserTokenResult:
        """Gets the Shared Access Authorization Token for the User.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param user_id: User identifier. Must be unique in the current API Management service instance.
         Required.
        :type user_id: str
        :param parameters: Create Authorization Token parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: UserTokenResult. The UserTokenResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.UserTokenResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def get_shared_access_token(
        self,
        resource_group_name: str,
        service_name: str,
        user_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.UserTokenResult:
        """Gets the Shared Access Authorization Token for the User.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param user_id: User identifier. Must be unique in the current API Management service instance.
         Required.
        :type user_id: str
        :param parameters: Create Authorization Token parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: UserTokenResult. The UserTokenResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.UserTokenResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def get_shared_access_token(
        self,
        resource_group_name: str,
        service_name: str,
        user_id: str,
        parameters: Union[_models.UserTokenParameters, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.UserTokenResult:
        """Gets the Shared Access Authorization Token for the User.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param user_id: User identifier. Must be unique in the current API Management service instance.
         Required.
        :type user_id: str
        :param parameters: Create Authorization Token parameters. Is one of the following types:
         UserTokenParameters, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.UserTokenParameters or JSON or IO[bytes]
        :return: UserTokenResult. The UserTokenResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.UserTokenResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.UserTokenResult] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_user_get_shared_access_token_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            user_id=user_id,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.UserTokenResult, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class UserGroupOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`user_group` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list(
        self,
        resource_group_name: str,
        service_name: str,
        user_id: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.GroupContract"]:
        """Lists all user groups.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param user_id: User identifier. Must be unique in the current API Management service instance.
         Required.
        :type user_id: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions
         |</br>|-------------|------------------------|-----------------------------------|</br>| name |
         filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>|
         displayName | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>| description | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
         endswith |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of GroupContract
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.GroupContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.GroupContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_user_group_list_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    user_id=user_id,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.GroupContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class UserIdentitiesOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`user_identities` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list(
        self, resource_group_name: str, service_name: str, user_id: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.UserIdentityContract"]:
        """List of all user identities.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param user_id: User identifier. Must be unique in the current API Management service instance.
         Required.
        :type user_id: str
        :return: An iterator like instance of UserIdentityContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.UserIdentityContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.UserIdentityContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_user_identities_list_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    user_id=user_id,
                    subscription_id=self._config.subscription_id,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.UserIdentityContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class UserConfirmationPasswordOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`user_confirmation_password` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def send(
        self,
        resource_group_name: str,
        service_name: str,
        user_id: str,
        *,
        app_type: Optional[Union[str, _models.AppType]] = None,
        **kwargs: Any
    ) -> None:
        """Sends confirmation.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param user_id: User identifier. Must be unique in the current API Management service instance.
         Required.
        :type user_id: str
        :keyword app_type: Determines the type of application which send the create user request.
         Default is legacy publisher portal. Known values are: "portal" and "developerPortal". Default
         value is None.
        :paramtype app_type: str or ~azure.mgmt.apimanagement.models.AppType
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_user_confirmation_password_send_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            user_id=user_id,
            subscription_id=self._config.subscription_id,
            app_type=app_type,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore


class ApiManagementWorkspaceLinkOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`api_management_workspace_link` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, workspace_id: str, **kwargs: Any
    ) -> _models.ApiManagementWorkspaceLinksResource:
        """Gets an API Management WorkspaceLink resource description.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :return: ApiManagementWorkspaceLinksResource. The ApiManagementWorkspaceLinksResource is
         compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiManagementWorkspaceLinksResource
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ApiManagementWorkspaceLinksResource] = kwargs.pop("cls", None)

        _request = build_api_management_workspace_link_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ApiManagementWorkspaceLinksResource, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class ApiManagementWorkspaceLinksOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`api_management_workspace_links` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list_by_service(
        self, resource_group_name: str, service_name: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.ApiManagementWorkspaceLinksResource"]:
        """List all API Management workspaceLinks for a service.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :return: An iterator like instance of ApiManagementWorkspaceLinksResource
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ApiManagementWorkspaceLinksResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ApiManagementWorkspaceLinksResource]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_api_management_workspace_links_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ApiManagementWorkspaceLinksResource],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class WorkspaceOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`workspace` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, resource_group_name: str, service_name: str, workspace_id: str, **kwargs: Any
    ) -> _models.WorkspaceContract:
        """Gets the details of the workspace specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :return: WorkspaceContract. The WorkspaceContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.WorkspaceContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.WorkspaceContract] = kwargs.pop("cls", None)

        _request = build_workspace_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.WorkspaceContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_entity_tag(
        self, resource_group_name: str, service_name: str, workspace_id: str, **kwargs: Any
    ) -> bool:
        """Gets the entity state (Etag) version of the workspace specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :return: bool
        :rtype: bool
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_get_entity_tag_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore
        return 200 <= response.status_code <= 299

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        parameters: _models.WorkspaceContract,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.WorkspaceContract:
        """Creates a new workspace or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param parameters: Create parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.WorkspaceContract
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: WorkspaceContract. The WorkspaceContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.WorkspaceContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.WorkspaceContract:
        """Creates a new workspace or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param parameters: Create parameters. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: WorkspaceContract. The WorkspaceContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.WorkspaceContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.WorkspaceContract:
        """Creates a new workspace or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param parameters: Create parameters. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: WorkspaceContract. The WorkspaceContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.WorkspaceContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        parameters: Union[_models.WorkspaceContract, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.WorkspaceContract:
        """Creates a new workspace or updates an existing one.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param parameters: Create parameters. Is one of the following types: WorkspaceContract, JSON,
         IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.WorkspaceContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: WorkspaceContract. The WorkspaceContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.WorkspaceContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.WorkspaceContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_create_or_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.WorkspaceContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        parameters: _models.WorkspaceContract,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.WorkspaceContract:
        """Updates the details of the workspace specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param parameters: Workspace Update parameters. Required.
        :type parameters: ~azure.mgmt.apimanagement.models.WorkspaceContract
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: WorkspaceContract. The WorkspaceContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.WorkspaceContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        parameters: JSON,
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.WorkspaceContract:
        """Updates the details of the workspace specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param parameters: Workspace Update parameters. Required.
        :type parameters: JSON
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: WorkspaceContract. The WorkspaceContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.WorkspaceContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        parameters: IO[bytes],
        *,
        etag: str,
        match_condition: MatchConditions,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.WorkspaceContract:
        """Updates the details of the workspace specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param parameters: Workspace Update parameters. Required.
        :type parameters: IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: WorkspaceContract. The WorkspaceContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.WorkspaceContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        parameters: Union[_models.WorkspaceContract, JSON, IO[bytes]],
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> _models.WorkspaceContract:
        """Updates the details of the workspace specified by its identifier.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param parameters: Workspace Update parameters. Is one of the following types:
         WorkspaceContract, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.apimanagement.models.WorkspaceContract or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: WorkspaceContract. The WorkspaceContract is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.WorkspaceContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.WorkspaceContract] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_workspace_update_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.WorkspaceContract, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        *,
        etag: str,
        match_condition: MatchConditions,
        **kwargs: Any
    ) -> None:
        """Deletes the specified workspace.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Required.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Required.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_workspace_delete_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            subscription_id=self._config.subscription_id,
            etag=etag,
            match_condition=match_condition,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_service(
        self,
        resource_group_name: str,
        service_name: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.WorkspaceContract"]:
        """Lists all workspaces of the API Management service instance.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :keyword filter: |     Field     |     Usage     |     Supported operators     |     Supported
         functions     |</br>|-------------|-------------|-------------|-------------|</br>| displayName
         | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br></br>|
         description | filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith
         |</br>. Default value is None.
        :paramtype filter: str
        :keyword top: Number of records to return. Default value is None.
        :paramtype top: int
        :keyword skip: Number of records to skip. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of WorkspaceContract
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.WorkspaceContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.WorkspaceContract]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_workspace_list_by_service_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.WorkspaceContract],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class ApiExportOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`api_export` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self,
        resource_group_name: str,
        service_name: str,
        api_id: str,
        *,
        format: Union[str, _models.ExportFormat],
        export: Union[str, _models.ExportApi],
        **kwargs: Any
    ) -> _models.ApiExportResult:
        """Gets the details of the API specified by its identifier in the format specified to the Storage
        Blob with SAS Key valid for 5 minutes.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :keyword format: Format in which to export the Api Details to the Storage Blob with Sas Key
         valid for 5 minutes. New formats can be added in the future. Known values are: "swagger-link",
         "wsdl-link", "wadl-link", "openapi-link", and "openapi+json-link". Required.
        :paramtype format: str or ~azure.mgmt.apimanagement.models.ExportFormat
        :keyword export: Query parameter required to export the API details. "true" Required.
        :paramtype export: str or ~azure.mgmt.apimanagement.models.ExportApi
        :return: ApiExportResult. The ApiExportResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiExportResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ApiExportResult] = kwargs.pop("cls", None)

        _request = build_api_export_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            api_id=api_id,
            subscription_id=self._config.subscription_id,
            format=format,
            export=export,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ApiExportResult, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class ApiManagementSkusOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`api_management_skus` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list(self, **kwargs: Any) -> AsyncItemPaged["_models.ApiManagementSku"]:
        """Gets the list of Microsoft.ApiManagement SKUs available for your Subscription.

        :return: An iterator like instance of ApiManagementSku
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ApiManagementSku]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ApiManagementSku]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_api_management_skus_list_request(
                    subscription_id=self._config.subscription_id,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ApiManagementSku],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class WorkspaceApiExportOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`workspace_api_export` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self,
        resource_group_name: str,
        service_name: str,
        workspace_id: str,
        api_id: str,
        *,
        format: Union[str, _models.ExportFormat],
        export: Union[str, _models.ExportApi],
        **kwargs: Any
    ) -> _models.ApiExportResult:
        """Gets the details of the API specified by its identifier in the format specified to the Storage
        Blob with SAS Key valid for 5 minutes.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param workspace_id: Workspace identifier. Must be unique in the current API Management service
         instance. Required.
        :type workspace_id: str
        :param api_id: API revision identifier. Must be unique in the current API Management service
         instance. Non-current revision has ;rev=n as a suffix where n is the revision number. Required.
        :type api_id: str
        :keyword format: Format in which to export the Api Details to the Storage Blob with Sas Key
         valid for 5 minutes. Known values are: "swagger-link", "wsdl-link", "wadl-link",
         "openapi-link", and "openapi+json-link". Required.
        :paramtype format: str or ~azure.mgmt.apimanagement.models.ExportFormat
        :keyword export: Query parameter required to export the API details. "true" Required.
        :paramtype export: str or ~azure.mgmt.apimanagement.models.ExportApi
        :return: ApiExportResult. The ApiExportResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.ApiExportResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ApiExportResult] = kwargs.pop("cls", None)

        _request = build_workspace_api_export_get_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            workspace_id=workspace_id,
            api_id=api_id,
            subscription_id=self._config.subscription_id,
            format=format,
            export=export,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ApiExportResult, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class OperationStatusOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`operation_status` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(self, location: str, operation_id: str, **kwargs: Any) -> _models.OperationStatusResult:
        """Returns the current status of an async operation.

        :param location: The name of the Azure region. Required.
        :type location: str
        :param operation_id: The ID of an ongoing async operation. Required.
        :type operation_id: str
        :return: OperationStatusResult. The OperationStatusResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.apimanagement.models.OperationStatusResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.OperationStatusResult] = kwargs.pop("cls", None)

        _request = build_operation_status_get_request(
            location=location,
            operation_id=operation_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.OperationStatusResult, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class OperationsResultsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`operations_results` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ApiManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(self, location: str, operation_id: str, **kwargs: Any) -> None:
        """Returns operation results for long running operations executing DELETE or PATCH on the
        resource.

        :param location: The name of the Azure region. Required.
        :type location: str
        :param operation_id: The ID of an ongoing async operation. Required.
        :type operation_id: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_operations_results_get_request(
            location=location,
            operation_id=operation_id,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))

        if cls:
            return cls(pipeline_response, None, response_headers)  # type: ignore


class _ApiManagementClientOperationsMixin(
    ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], ApiManagementClientConfiguration]
):

    async def _perform_connectivity_check_async_initial(  # pylint: disable=name-too-long
        self,
        resource_group_name: str,
        service_name: str,
        connectivity_check_request_params: Union[_models.ConnectivityCheckRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(connectivity_check_request_params, (IOBase, bytes)):
            _content = connectivity_check_request_params
        else:
            _content = json.dumps(connectivity_check_request_params, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_api_management_perform_connectivity_check_async_request(
            resource_group_name=resource_group_name,
            service_name=service_name,
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_perform_connectivity_check_async(
        self,
        resource_group_name: str,
        service_name: str,
        connectivity_check_request_params: _models.ConnectivityCheckRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ConnectivityCheckResponse]:
        """Performs a connectivity check between the API Management service and a given destination, and
        returns metrics for the connection, as well as errors encountered while trying to establish it.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param connectivity_check_request_params: Connectivity Check request parameters. Required.
        :type connectivity_check_request_params:
         ~azure.mgmt.apimanagement.models.ConnectivityCheckRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns ConnectivityCheckResponse. The
         ConnectivityCheckResponse is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ConnectivityCheckResponse]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_perform_connectivity_check_async(
        self,
        resource_group_name: str,
        service_name: str,
        connectivity_check_request_params: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ConnectivityCheckResponse]:
        """Performs a connectivity check between the API Management service and a given destination, and
        returns metrics for the connection, as well as errors encountered while trying to establish it.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param connectivity_check_request_params: Connectivity Check request parameters. Required.
        :type connectivity_check_request_params: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns ConnectivityCheckResponse. The
         ConnectivityCheckResponse is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ConnectivityCheckResponse]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_perform_connectivity_check_async(
        self,
        resource_group_name: str,
        service_name: str,
        connectivity_check_request_params: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ConnectivityCheckResponse]:
        """Performs a connectivity check between the API Management service and a given destination, and
        returns metrics for the connection, as well as errors encountered while trying to establish it.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param connectivity_check_request_params: Connectivity Check request parameters. Required.
        :type connectivity_check_request_params: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns ConnectivityCheckResponse. The
         ConnectivityCheckResponse is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ConnectivityCheckResponse]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_perform_connectivity_check_async(
        self,
        resource_group_name: str,
        service_name: str,
        connectivity_check_request_params: Union[_models.ConnectivityCheckRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ConnectivityCheckResponse]:
        """Performs a connectivity check between the API Management service and a given destination, and
        returns metrics for the connection, as well as errors encountered while trying to establish it.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param connectivity_check_request_params: Connectivity Check request parameters. Is one of the
         following types: ConnectivityCheckRequest, JSON, IO[bytes] Required.
        :type connectivity_check_request_params:
         ~azure.mgmt.apimanagement.models.ConnectivityCheckRequest or JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns ConnectivityCheckResponse. The
         ConnectivityCheckResponse is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.ConnectivityCheckResponse]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ConnectivityCheckResponse] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._perform_connectivity_check_async_initial(
                resource_group_name=resource_group_name,
                service_name=service_name,
                connectivity_check_request_params=connectivity_check_request_params,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response_headers = {}
            response = pipeline_response.http_response
            response_headers["location"] = self._deserialize("str", response.headers.get("location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

            deserialized = _deserialize(_models.ConnectivityCheckResponse, response.json())
            if cls:
                return cls(pipeline_response, deserialized, response_headers)  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.ConnectivityCheckResponse].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.ConnectivityCheckResponse](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )
