azure-maps-search


Nameazure-maps-search JSON
Version 2.0.0b2 PyPI version JSON
download
home_pagehttps://github.com/Azure/azure-sdk-for-python/tree/main/sdk/maps/azure-maps-search
SummaryMicrosoft Azure Maps Search Client Library for Python
upload_time2024-12-12 00:31:40
maintainerNone
docs_urlNone
authorMicrosoft Corporation
requires_python>=3.8
licenseMIT License
keywords azure azure sdk
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage
            # Azure Maps Search Package client library for Python

This package contains a Python SDK for Azure Maps Services for Search.
Read more about Azure Maps Services [here](https://docs.microsoft.com/azure/azure-maps/)

[Source code](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/maps/azure-maps-search) | [API reference documentation](https://docs.microsoft.com/rest/api/maps/search) | [Product documentation](https://docs.microsoft.com/azure/azure-maps/)

## _Disclaimer_

_Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer to <https://github.com/Azure/azure-sdk-for-python/issues/20691>_

## Getting started

### Prerequisites

- Python 3.8 or later is required to use this package.
- An [Azure subscription][azure_subscription] and an [Azure Maps account](https://docs.microsoft.com/azure/azure-maps/how-to-manage-account-keys).
- A deployed Maps Services resource. You can create the resource via [Azure Portal][azure_portal] or [Azure CLI][azure_cli].

If you use Azure CLI, replace `<resource-group-name>` and `<account-name>` of your choice, and select a proper [pricing tier](https://docs.microsoft.com/azure/azure-maps/choose-pricing-tier) based on your needs via the `<sku-name>` parameter. Please refer to [this page](https://docs.microsoft.com/cli/azure/maps/account?view=azure-cli-latest#az_maps_account_create) for more details.

```bash
az maps account create --resource-group <resource-group-name> --account-name <account-name> --sku <sku-name>
```

### Install the package

Install the Azure Maps Service Search SDK.

```bash
pip install azure-maps-search
```

### Create and Authenticate the MapsSearchClient

To create a client object to access the Azure Maps Search API, you will need a **credential** object. Azure Maps Search client also support three ways to authenticate.

#### 1. Authenticate with a Subscription Key Credential

You can authenticate with your Azure Maps Subscription Key.
Once the Azure Maps Subscription Key is created, set the value of the key as environment variable: `AZURE_SUBSCRIPTION_KEY`.
Then pass an `AZURE_SUBSCRIPTION_KEY` as the `credential` parameter into an instance of [AzureKeyCredential][azure-key-credential].

```python
from azure.core.credentials import AzureKeyCredential
from azure.maps.search import MapsSearchClient

credential = AzureKeyCredential(os.environ.get("AZURE_SUBSCRIPTION_KEY"))

search_client = MapsSearchClient(
    credential=credential,
)
```

#### 2. Authenticate with a SAS Credential

Shared access signature (SAS) tokens are authentication tokens created using the JSON Web token (JWT) format and are cryptographically signed to prove authentication for an application to the Azure Maps REST API.

To authenticate with a SAS token in Python, you'll need to generate one using the azure-mgmt-maps package. 

We need to tell user to install `azure-mgmt-maps`: `pip install azure-mgmt-maps`

Here's how you can generate the SAS token using the list_sas method from azure-mgmt-maps:

```python
from azure.identity import DefaultAzureCredential
from azure.mgmt.maps import AzureMapsManagementClient

"""
# PREREQUISITES
    pip install azure-identity
    pip install azure-mgmt-maps
# USAGE
    python account_list_sas.py
    Before run the sample, please set the values of the client ID, tenant ID and client secret
    of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
    AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
    https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""


def main():
    client = AzureMapsManagementClient(
        credential=DefaultAzureCredential(),
        subscription_id="your-subscription-id",
    )

    response = client.accounts.list_sas(
        resource_group_name="myResourceGroup",
        account_name="myMapsAccount",
        maps_account_sas_parameters={
            "expiry": "2017-05-24T11:42:03.1567373Z",
            "maxRatePerSecond": 500,
            "principalId": "your-principal-id",
            "regions": ["eastus"],
            "signingKey": "primaryKey",
            "start": "2017-05-24T10:42:03.1567373Z",
        },
    )
    print(response)
```

Once the SAS token is created, set the value of the token as environment variable: `AZURE_SAS_TOKEN`.
Then pass an `AZURE_SAS_TOKEN` as the `credential` parameter into an instance of AzureSasCredential.

```python
import os

from azure.core.credentials import AzureSASCredential
from azure.maps.search import MapsSearchClient

credential = AzureSASCredential(os.environ.get("AZURE_SAS_TOKEN"))

search_client = MapsSearchClient(
    credential=credential,
)
```

#### 3. Authenticate with an Microsoft Entra ID credential

You can authenticate with [Microsoft Entra ID token credential][maps_authentication_microsoft_entra_id] using the [Azure Identity library][azure_identity].
Authentication by using Microsoft Entra ID requires some initial setup:

- Install [azure-identity][azure-key-credential]
- Register a [new Microsoft Entra ID application][register_microsoft_entra_id_app]
- Grant access to Azure Maps by assigning the suitable role to your service principal. Please refer to the [Manage authentication page][manage_microsoft_entra_id_auth_page].

After setup, you can choose which type of [credential][azure-key-credential] from `azure.identity` to use.
As an example, [DefaultAzureCredential][default_azure_credential]
can be used to authenticate the client:

Next, set the values of the client ID, tenant ID, and client secret of the Microsoft Entra ID application as environment variables:
`AZURE_CLIENT_ID`, `AZURE_TENANT_ID`, `AZURE_CLIENT_SECRET`

You will also need to specify the Azure Maps resource you intend to use by specifying the `clientId` in the client options. The Azure Maps resource client id can be found in the Authentication sections in the Azure Maps resource. Please refer to the [documentation][how_to_manage_authentication] on how to find it.

```python
from azure.maps.search import MapsSearchClient
from azure.identity import DefaultAzureCredential

credential = DefaultAzureCredential()
search_client = MapsSearchClient(credential=credential)
```

## Key concepts

The Azure Maps Search client library for Python allows you to interact with each of the components through the use of a dedicated client object.

### Sync Clients

`MapsSearchClient` is the primary client for developers using the Azure Maps Search client library for Python.
Once you initialized a `MapsSearchClient` class, you can explore the methods on this client object to understand the different features of the Azure Maps Search service that you can access.

### Async Clients

This library includes a complete async API supported on Python 3.5+. To use it, you must first install an async transport, such as [aiohttp](https://pypi.org/project/aiohttp/).
See [azure-core documentation](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/core/azure-core/CLIENT_LIBRARY_DEVELOPER.md#transport) for more information.

Async clients and credentials should be closed when they're no longer needed. These objects are async context managers and define async `close` methods.

## Examples

The following sections provide several code snippets covering some of the most common Azure Maps Search tasks, including:

- [Geocode an address](#geocode-an-address)
- [Batch geocode addresses](#batch-geocode-addresses)
- [Get polygons for a given location](#get-polygons-for-a-given-location)
- [Make a Reverse Address Search to translate coordinate location to street address](#make-a-reverse-address-search-to-translate-coordinate-location-to-street-address)
- [Batch request for reverse geocoding](#batch-request-for-reverse-geocoding)

### Geocode an address

You can use an authenticated client to convert an address into latitude and longitude coordinates. This process is also called geocoding. In addition to returning the coordinates, the response will also return detailed address properties such as street, postal code, municipality, and country/region information.

```python
import os

from azure.core.exceptions import HttpResponseError

subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY", "your subscription key")

def geocode():
    from azure.core.credentials import AzureKeyCredential
    from azure.maps.search import MapsSearchClient

    maps_search_client = MapsSearchClient(credential=AzureKeyCredential(subscription_key))
    try:
        result = maps_search_client.get_geocoding(query="15127 NE 24th Street, Redmond, WA 98052")
        if result.get('features', False):
            coordinates = result['features'][0]['geometry']['coordinates']
            longitude = coordinates[0]
            latitude = coordinates[1]

            print(longitude, latitude)
        else:
            print("No results")

    except HttpResponseError as exception:
        if exception.error is not None:
            print(f"Error Code: {exception.error.code}")
            print(f"Message: {exception.error.message}")

if __name__ == '__main__':
    geocode()
```

### Batch geocode addresses

This sample demonstrates how to perform batch search address.

```python
import os

from azure.core.exceptions import HttpResponseError

subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY", "your subscription key")

def geocode_batch():
    from azure.core.credentials import AzureKeyCredential
    from azure.maps.search import MapsSearchClient

    maps_search_client = MapsSearchClient(credential=AzureKeyCredential(subscription_key))
    try:
        result = maps_search_client.get_geocoding_batch({
          "batchItems": [
            {"query": "400 Broad St, Seattle, WA 98109"},
            {"query": "15127 NE 24th Street, Redmond, WA 98052"},
          ],
        },)

        if not result.get('batchItems', False):
            print("No batchItems in geocoding")
            return

        for item in result['batchItems']:
            if not item.get('features', False):
                print(f"No features in item: {item}")
                continue

            coordinates = item['features'][0]['geometry']['coordinates']
            longitude, latitude = coordinates
            print(longitude, latitude)

    except HttpResponseError as exception:
        if exception.error is not None:
            print(f"Error Code: {exception.error.code}")
            print(f"Message: {exception.error.message}")

if __name__ == '__main__':
    geocode_batch()
```

### Get polygons for a given location

This sample demonstrates how to search polygons.

```python
import os

from azure.core.exceptions import HttpResponseError
from azure.maps.search import Resolution
from azure.maps.search import BoundaryResultType


subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY", "your subscription key")

def get_polygon():
    from azure.core.credentials import AzureKeyCredential
    from azure.maps.search import MapsSearchClient

    maps_search_client = MapsSearchClient(credential=AzureKeyCredential(subscription_key))
    try:
        result = maps_search_client.get_polygon(
          coordinates=[-122.204141, 47.61256],
          result_type=BoundaryResultType.LOCALITY,
          resolution=Resolution.SMALL,
        )

        if not result.get('geometry', False):
            print("No geometry found")
            return

        print(result["geometry"])
    except HttpResponseError as exception:
        if exception.error is not None:
            print(f"Error Code: {exception.error.code}")
            print(f"Message: {exception.error.message}")

if __name__ == '__main__':
    get_polygon()
```

### Make a Reverse Address Search to translate coordinate location to street address

You can translate coordinates into human-readable street addresses. This process is also called reverse geocoding. This is often used for applications that consume GPS feeds and want to discover addresses at specific coordinate points.

```python
import os

from azure.core.exceptions import HttpResponseError

subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY", "your subscription key")

def reverse_geocode():
    from azure.core.credentials import AzureKeyCredential
    from azure.maps.search import MapsSearchClient

    maps_search_client = MapsSearchClient(credential=AzureKeyCredential(subscription_key))
    try:
        result = maps_search_client.get_reverse_geocoding(coordinates=[-122.138679, 47.630356])
        if result.get('features', False):
            props = result['features'][0].get('properties', {})
            if props and props.get('address', False):
                print(props['address'].get('formattedAddress', 'No formatted address found'))
            else:
                print("Address is None")
        else:
            print("No features available")
    except HttpResponseError as exception:
        if exception.error is not None:
            print(f"Error Code: {exception.error.code}")
            print(f"Message: {exception.error.message}")


if __name__ == '__main__':
   reverse_geocode()
```

### Batch request for reverse geocoding

This sample demonstrates how to perform reverse search by given coordinates in batch.

```python
import os
from azure.core.credentials import AzureKeyCredential
from azure.core.exceptions import HttpResponseError
from azure.maps.search import MapsSearchClient

subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY", "your subscription key")

def reverse_geocode_batch():
    maps_search_client = MapsSearchClient(credential=AzureKeyCredential(subscription_key))
    try:
        result = maps_search_client.get_reverse_geocoding_batch({
              "batchItems": [
                {"coordinates": [-122.349309, 47.620498]},
                {"coordinates": [-122.138679, 47.630356]},
              ],
            },)

        if result.get('batchItems', False):
            for idx, item in enumerate(result['batchItems']):
                features = item['features']
                if features:
                    props = features[0].get('properties', {})
                    if props and props.get('address', False):
                        print(
                            props['address'].get('formattedAddress', f'No formatted address for item {idx + 1} found'))
                    else:
                        print(f"Address {idx + 1} is None")
                else:
                    print(f"No features available for item {idx + 1}")
        else:
            print("No batch items found")
    except HttpResponseError as exception:
        if exception.error is not None:
            print(f"Error Code: {exception.error.code}")
            print(f"Message: {exception.error.message}")


if __name__ == '__main__':
   reverse_geocode_batch()
```

## Troubleshooting

### General

Maps Search clients raise exceptions defined in [Azure Core](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/core/azure-core/README.md).

This list can be used for reference to catch thrown exceptions. To get the specific error code of the exception, use the `error_code` attribute, i.e, `exception.error_code`.

### Logging

This library uses the standard [logging](https://docs.python.org/3/library/logging.html) library for logging.
Basic information about HTTP sessions (URLs, headers, etc.) is logged at INFO level.

Detailed DEBUG level logging, including request/response bodies and unredacted headers, can be enabled on a client with the `logging_enable` argument:

```python
import sys
import logging
from azure.maps.search import MapsSearchClient

# Create a logger for the 'azure.maps.search' SDK
logger = logging.getLogger('azure.maps.search')
logger.setLevel(logging.DEBUG)

# Configure a console output
handler = logging.StreamHandler(stream=sys.stdout)
logger.addHandler(handler)

```

Similarly, `logging_enable` can enable detailed logging for a single operation,
even when it isn't enabled for the client:

```python
service_client.get_service_stats(logging_enable=True)
```

### Additional

Still running into issues? If you encounter any bugs or have suggestions, please file an issue in the [Issues](<https://github.com/Azure/azure-sdk-for-python/issues>) section of the project.

## Next steps

### More sample code

Get started with our [Maps Search samples](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/maps/azure-maps-search/samples) ([Async Version samples](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/maps/azure-maps-search/samples/async_samples)).

Several Azure Maps Search Python SDK samples are available to you in the SDK's GitHub repository. These samples provide example code for additional scenarios commonly encountered while working with Maps Search

```bash
set AZURE_SUBSCRIPTION_KEY="<RealSubscriptionKey>"

pip install azure-maps-search --pre

python samples/sample_geocode.py
python samples/sample_geocode_batch.py
python samples/sample_get_polygon.py
python samples/sample_reverse_geocode.py
python samples/sample_reverse_geocode_batch.py
```

> Notes: `--pre` flag can be optionally added, it is to include pre-release and development versions for `pip install`. By default, `pip` only finds stable versions.

Further detail please refer to [Samples Introduction](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/maps/azure-maps-search/samples/README.md)

### Additional documentation

For more extensive documentation on Azure Maps Search, see the [Azure Maps Search documentation](https://docs.microsoft.com/rest/api/maps/search) on docs.microsoft.com.

## Contributing

This project welcomes contributions and suggestions.  Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit <https://cla.microsoft.com>.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.

<!-- LINKS -->
[azure_subscription]: https://azure.microsoft.com/free/
[azure_identity]: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/identity/azure-identity
[azure_portal]: https://portal.azure.com
[azure_cli]: https://docs.microsoft.com/cli/azure
[azure-key-credential]: https://aka.ms/azsdk/python/core/azurekeycredential
[default_azure_credential]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity#defaultazurecredential
[register_microsoft_entra_id_app]: https://docs.microsoft.com/powershell/module/Az.Resources/New-AzADApplication?view=azps-8.0.0
[maps_authentication_microsoft_entra_id]: https://docs.microsoft.com/azure/azure-maps/how-to-manage-authentication
[create_new_application_registration]: https://portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/applicationsListBlade/quickStartType/AspNetWebAppQuickstartPage/sourceType/docs
[manage_microsoft_entra_id_auth_page]: https://docs.microsoft.com/azure/azure-maps/how-to-manage-authentication
[how_to_manage_authentication]: https://docs.microsoft.com/azure/azure-maps/how-to-manage-authentication#view-authentication-details


# Release History

## 2.0.0b2 (2024-12-12)

### Features Added

- Integrated support for SAS-based authentication

## 2.0.0b1 (2024-08-06)

### New Features and Enhancements

- Support Search API `2023-06-01`

- **Geocoding APIs**
  - Introduced `get_geocoding` method to obtain longitude and latitude coordinates for a given address.
  - Introduced `get_geocoding_batch` method to handle batch geocoding queries, supporting up to 100 queries in a single request.

- **Reverse Geocoding APIs**
  - Introduced `get_reverse_geocoding` method to get address details from given coordinates.
  - Introduced `get_reverse_geocoding_batch` method to handle batch reverse geocoding queries, supporting up to 100 queries in a single request.

- **Boundary APIs**
  - Introduced `get_polygon` method to obtain polygon boundaries for a given set of coordinates with specified resolution and boundary result type.

### Breaking Changes

- **Removed Methods**
  - Removed the `fuzzy_search` method.
  - Removed the `search_point_of_interest` method.
  - Removed the `search_address` method.
  - Removed the `search_nearby_point_of_interest` method.
  - Removed the `search_point_of_interest_category` method.
  - Removed the `search_structured_address` method.
  - Removed the `get_geometries` method.
  - Removed the `get_point_of_interest_categories` method.
  - Removed the `reverse_search_address` method.
  - Removed the `reverse_search_cross_street_address` method.
  - Removed the `search_inside_geometry` method.
  - Removed the `search_along_route` method.
  - Removed the `fuzzy_search_batch` method.
  - Removed the `search_address_batch` method.

## 1.0.0b3 (2024-05-15)
 
### Bugs Fixed

- Fix response validation error for reverse search address

### Other Changes

- Fix reverse search sample in README.md
- Fix Sphinx errors
- Fix pylint errors for pylint version 2.15.8

## 1.0.0b2 (2022-10-11)

### Other Changes

- Update the tests using new test proxy
- Update Doc strings

## 1.0.0b1 (2022-09-06)

- Initial Release

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/maps/azure-maps-search",
    "name": "azure-maps-search",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": "azure, azure sdk",
    "author": "Microsoft Corporation",
    "author_email": "azpysdkhelp@microsoft.com",
    "download_url": "https://files.pythonhosted.org/packages/3f/fd/6583db00209220e636786595eb5f505c0b2fead421ab01c6ef250a847a0d/azure_maps_search-2.0.0b2.tar.gz",
    "platform": null,
    "description": "# Azure Maps Search Package client library for Python\n\nThis package contains a Python SDK for Azure Maps Services for Search.\nRead more about Azure Maps Services [here](https://docs.microsoft.com/azure/azure-maps/)\n\n[Source code](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/maps/azure-maps-search) | [API reference documentation](https://docs.microsoft.com/rest/api/maps/search) | [Product documentation](https://docs.microsoft.com/azure/azure-maps/)\n\n## _Disclaimer_\n\n_Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer to <https://github.com/Azure/azure-sdk-for-python/issues/20691>_\n\n## Getting started\n\n### Prerequisites\n\n- Python 3.8 or later is required to use this package.\n- An [Azure subscription][azure_subscription] and an [Azure Maps account](https://docs.microsoft.com/azure/azure-maps/how-to-manage-account-keys).\n- A deployed Maps Services resource. You can create the resource via [Azure Portal][azure_portal] or [Azure CLI][azure_cli].\n\nIf you use Azure CLI, replace `<resource-group-name>` and `<account-name>` of your choice, and select a proper [pricing tier](https://docs.microsoft.com/azure/azure-maps/choose-pricing-tier) based on your needs via the `<sku-name>` parameter. Please refer to [this page](https://docs.microsoft.com/cli/azure/maps/account?view=azure-cli-latest#az_maps_account_create) for more details.\n\n```bash\naz maps account create --resource-group <resource-group-name> --account-name <account-name> --sku <sku-name>\n```\n\n### Install the package\n\nInstall the Azure Maps Service Search SDK.\n\n```bash\npip install azure-maps-search\n```\n\n### Create and Authenticate the MapsSearchClient\n\nTo create a client object to access the Azure Maps Search API, you will need a **credential** object. Azure Maps Search client also support three ways to authenticate.\n\n#### 1. Authenticate with a Subscription Key Credential\n\nYou can authenticate with your Azure Maps Subscription Key.\nOnce the Azure Maps Subscription Key is created, set the value of the key as environment variable: `AZURE_SUBSCRIPTION_KEY`.\nThen pass an `AZURE_SUBSCRIPTION_KEY` as the `credential` parameter into an instance of [AzureKeyCredential][azure-key-credential].\n\n```python\nfrom azure.core.credentials import AzureKeyCredential\nfrom azure.maps.search import MapsSearchClient\n\ncredential = AzureKeyCredential(os.environ.get(\"AZURE_SUBSCRIPTION_KEY\"))\n\nsearch_client = MapsSearchClient(\n    credential=credential,\n)\n```\n\n#### 2. Authenticate with a SAS Credential\n\nShared access signature (SAS) tokens are authentication tokens created using the JSON Web token (JWT) format and are cryptographically signed to prove authentication for an application to the Azure Maps REST API.\n\nTo authenticate with a SAS token in Python, you'll need to generate one using the azure-mgmt-maps package. \n\nWe need to tell user to install `azure-mgmt-maps`: `pip install azure-mgmt-maps`\n\nHere's how you can generate the SAS token using the list_sas method from azure-mgmt-maps:\n\n```python\nfrom azure.identity import DefaultAzureCredential\nfrom azure.mgmt.maps import AzureMapsManagementClient\n\n\"\"\"\n# PREREQUISITES\n    pip install azure-identity\n    pip install azure-mgmt-maps\n# USAGE\n    python account_list_sas.py\n    Before run the sample, please set the values of the client ID, tenant ID and client secret\n    of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,\n    AZURE_CLIENT_SECRET. For more info about how to get the value, please see:\n    https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal\n\"\"\"\n\n\ndef main():\n    client = AzureMapsManagementClient(\n        credential=DefaultAzureCredential(),\n        subscription_id=\"your-subscription-id\",\n    )\n\n    response = client.accounts.list_sas(\n        resource_group_name=\"myResourceGroup\",\n        account_name=\"myMapsAccount\",\n        maps_account_sas_parameters={\n            \"expiry\": \"2017-05-24T11:42:03.1567373Z\",\n            \"maxRatePerSecond\": 500,\n            \"principalId\": \"your-principal-id\",\n            \"regions\": [\"eastus\"],\n            \"signingKey\": \"primaryKey\",\n            \"start\": \"2017-05-24T10:42:03.1567373Z\",\n        },\n    )\n    print(response)\n```\n\nOnce the SAS token is created, set the value of the token as environment variable: `AZURE_SAS_TOKEN`.\nThen pass an `AZURE_SAS_TOKEN` as the `credential` parameter into an instance of AzureSasCredential.\n\n```python\nimport os\n\nfrom azure.core.credentials import AzureSASCredential\nfrom azure.maps.search import MapsSearchClient\n\ncredential = AzureSASCredential(os.environ.get(\"AZURE_SAS_TOKEN\"))\n\nsearch_client = MapsSearchClient(\n    credential=credential,\n)\n```\n\n#### 3. Authenticate with an Microsoft Entra ID credential\n\nYou can authenticate with [Microsoft Entra ID token credential][maps_authentication_microsoft_entra_id] using the [Azure Identity library][azure_identity].\nAuthentication by using Microsoft Entra ID requires some initial setup:\n\n- Install [azure-identity][azure-key-credential]\n- Register a [new Microsoft Entra ID application][register_microsoft_entra_id_app]\n- Grant access to Azure Maps by assigning the suitable role to your service principal. Please refer to the [Manage authentication page][manage_microsoft_entra_id_auth_page].\n\nAfter setup, you can choose which type of [credential][azure-key-credential] from `azure.identity` to use.\nAs an example, [DefaultAzureCredential][default_azure_credential]\ncan be used to authenticate the client:\n\nNext, set the values of the client ID, tenant ID, and client secret of the Microsoft Entra ID application as environment variables:\n`AZURE_CLIENT_ID`, `AZURE_TENANT_ID`, `AZURE_CLIENT_SECRET`\n\nYou will also need to specify the Azure Maps resource you intend to use by specifying the `clientId` in the client options. The Azure Maps resource client id can be found in the Authentication sections in the Azure Maps resource. Please refer to the [documentation][how_to_manage_authentication] on how to find it.\n\n```python\nfrom azure.maps.search import MapsSearchClient\nfrom azure.identity import DefaultAzureCredential\n\ncredential = DefaultAzureCredential()\nsearch_client = MapsSearchClient(credential=credential)\n```\n\n## Key concepts\n\nThe Azure Maps Search client library for Python allows you to interact with each of the components through the use of a dedicated client object.\n\n### Sync Clients\n\n`MapsSearchClient` is the primary client for developers using the Azure Maps Search client library for Python.\nOnce you initialized a `MapsSearchClient` class, you can explore the methods on this client object to understand the different features of the Azure Maps Search service that you can access.\n\n### Async Clients\n\nThis library includes a complete async API supported on Python 3.5+. To use it, you must first install an async transport, such as [aiohttp](https://pypi.org/project/aiohttp/).\nSee [azure-core documentation](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/core/azure-core/CLIENT_LIBRARY_DEVELOPER.md#transport) for more information.\n\nAsync clients and credentials should be closed when they're no longer needed. These objects are async context managers and define async `close` methods.\n\n## Examples\n\nThe following sections provide several code snippets covering some of the most common Azure Maps Search tasks, including:\n\n- [Geocode an address](#geocode-an-address)\n- [Batch geocode addresses](#batch-geocode-addresses)\n- [Get polygons for a given location](#get-polygons-for-a-given-location)\n- [Make a Reverse Address Search to translate coordinate location to street address](#make-a-reverse-address-search-to-translate-coordinate-location-to-street-address)\n- [Batch request for reverse geocoding](#batch-request-for-reverse-geocoding)\n\n### Geocode an address\n\nYou can use an authenticated client to convert an address into latitude and longitude coordinates. This process is also called geocoding. In addition to returning the coordinates, the response will also return detailed address properties such as street, postal code, municipality, and country/region information.\n\n```python\nimport os\n\nfrom azure.core.exceptions import HttpResponseError\n\nsubscription_key = os.getenv(\"AZURE_SUBSCRIPTION_KEY\", \"your subscription key\")\n\ndef geocode():\n    from azure.core.credentials import AzureKeyCredential\n    from azure.maps.search import MapsSearchClient\n\n    maps_search_client = MapsSearchClient(credential=AzureKeyCredential(subscription_key))\n    try:\n        result = maps_search_client.get_geocoding(query=\"15127 NE 24th Street, Redmond, WA 98052\")\n        if result.get('features', False):\n            coordinates = result['features'][0]['geometry']['coordinates']\n            longitude = coordinates[0]\n            latitude = coordinates[1]\n\n            print(longitude, latitude)\n        else:\n            print(\"No results\")\n\n    except HttpResponseError as exception:\n        if exception.error is not None:\n            print(f\"Error Code: {exception.error.code}\")\n            print(f\"Message: {exception.error.message}\")\n\nif __name__ == '__main__':\n    geocode()\n```\n\n### Batch geocode addresses\n\nThis sample demonstrates how to perform batch search address.\n\n```python\nimport os\n\nfrom azure.core.exceptions import HttpResponseError\n\nsubscription_key = os.getenv(\"AZURE_SUBSCRIPTION_KEY\", \"your subscription key\")\n\ndef geocode_batch():\n    from azure.core.credentials import AzureKeyCredential\n    from azure.maps.search import MapsSearchClient\n\n    maps_search_client = MapsSearchClient(credential=AzureKeyCredential(subscription_key))\n    try:\n        result = maps_search_client.get_geocoding_batch({\n          \"batchItems\": [\n            {\"query\": \"400 Broad St, Seattle, WA 98109\"},\n            {\"query\": \"15127 NE 24th Street, Redmond, WA 98052\"},\n          ],\n        },)\n\n        if not result.get('batchItems', False):\n            print(\"No batchItems in geocoding\")\n            return\n\n        for item in result['batchItems']:\n            if not item.get('features', False):\n                print(f\"No features in item: {item}\")\n                continue\n\n            coordinates = item['features'][0]['geometry']['coordinates']\n            longitude, latitude = coordinates\n            print(longitude, latitude)\n\n    except HttpResponseError as exception:\n        if exception.error is not None:\n            print(f\"Error Code: {exception.error.code}\")\n            print(f\"Message: {exception.error.message}\")\n\nif __name__ == '__main__':\n    geocode_batch()\n```\n\n### Get polygons for a given location\n\nThis sample demonstrates how to search polygons.\n\n```python\nimport os\n\nfrom azure.core.exceptions import HttpResponseError\nfrom azure.maps.search import Resolution\nfrom azure.maps.search import BoundaryResultType\n\n\nsubscription_key = os.getenv(\"AZURE_SUBSCRIPTION_KEY\", \"your subscription key\")\n\ndef get_polygon():\n    from azure.core.credentials import AzureKeyCredential\n    from azure.maps.search import MapsSearchClient\n\n    maps_search_client = MapsSearchClient(credential=AzureKeyCredential(subscription_key))\n    try:\n        result = maps_search_client.get_polygon(\n          coordinates=[-122.204141, 47.61256],\n          result_type=BoundaryResultType.LOCALITY,\n          resolution=Resolution.SMALL,\n        )\n\n        if not result.get('geometry', False):\n            print(\"No geometry found\")\n            return\n\n        print(result[\"geometry\"])\n    except HttpResponseError as exception:\n        if exception.error is not None:\n            print(f\"Error Code: {exception.error.code}\")\n            print(f\"Message: {exception.error.message}\")\n\nif __name__ == '__main__':\n    get_polygon()\n```\n\n### Make a Reverse Address Search to translate coordinate location to street address\n\nYou can translate coordinates into human-readable street addresses. This process is also called reverse geocoding. This is often used for applications that consume GPS feeds and want to discover addresses at specific coordinate points.\n\n```python\nimport os\n\nfrom azure.core.exceptions import HttpResponseError\n\nsubscription_key = os.getenv(\"AZURE_SUBSCRIPTION_KEY\", \"your subscription key\")\n\ndef reverse_geocode():\n    from azure.core.credentials import AzureKeyCredential\n    from azure.maps.search import MapsSearchClient\n\n    maps_search_client = MapsSearchClient(credential=AzureKeyCredential(subscription_key))\n    try:\n        result = maps_search_client.get_reverse_geocoding(coordinates=[-122.138679, 47.630356])\n        if result.get('features', False):\n            props = result['features'][0].get('properties', {})\n            if props and props.get('address', False):\n                print(props['address'].get('formattedAddress', 'No formatted address found'))\n            else:\n                print(\"Address is None\")\n        else:\n            print(\"No features available\")\n    except HttpResponseError as exception:\n        if exception.error is not None:\n            print(f\"Error Code: {exception.error.code}\")\n            print(f\"Message: {exception.error.message}\")\n\n\nif __name__ == '__main__':\n   reverse_geocode()\n```\n\n### Batch request for reverse geocoding\n\nThis sample demonstrates how to perform reverse search by given coordinates in batch.\n\n```python\nimport os\nfrom azure.core.credentials import AzureKeyCredential\nfrom azure.core.exceptions import HttpResponseError\nfrom azure.maps.search import MapsSearchClient\n\nsubscription_key = os.getenv(\"AZURE_SUBSCRIPTION_KEY\", \"your subscription key\")\n\ndef reverse_geocode_batch():\n    maps_search_client = MapsSearchClient(credential=AzureKeyCredential(subscription_key))\n    try:\n        result = maps_search_client.get_reverse_geocoding_batch({\n              \"batchItems\": [\n                {\"coordinates\": [-122.349309, 47.620498]},\n                {\"coordinates\": [-122.138679, 47.630356]},\n              ],\n            },)\n\n        if result.get('batchItems', False):\n            for idx, item in enumerate(result['batchItems']):\n                features = item['features']\n                if features:\n                    props = features[0].get('properties', {})\n                    if props and props.get('address', False):\n                        print(\n                            props['address'].get('formattedAddress', f'No formatted address for item {idx + 1} found'))\n                    else:\n                        print(f\"Address {idx + 1} is None\")\n                else:\n                    print(f\"No features available for item {idx + 1}\")\n        else:\n            print(\"No batch items found\")\n    except HttpResponseError as exception:\n        if exception.error is not None:\n            print(f\"Error Code: {exception.error.code}\")\n            print(f\"Message: {exception.error.message}\")\n\n\nif __name__ == '__main__':\n   reverse_geocode_batch()\n```\n\n## Troubleshooting\n\n### General\n\nMaps Search clients raise exceptions defined in [Azure Core](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/core/azure-core/README.md).\n\nThis list can be used for reference to catch thrown exceptions. To get the specific error code of the exception, use the `error_code` attribute, i.e, `exception.error_code`.\n\n### Logging\n\nThis library uses the standard [logging](https://docs.python.org/3/library/logging.html) library for logging.\nBasic information about HTTP sessions (URLs, headers, etc.) is logged at INFO level.\n\nDetailed DEBUG level logging, including request/response bodies and unredacted headers, can be enabled on a client with the `logging_enable` argument:\n\n```python\nimport sys\nimport logging\nfrom azure.maps.search import MapsSearchClient\n\n# Create a logger for the 'azure.maps.search' SDK\nlogger = logging.getLogger('azure.maps.search')\nlogger.setLevel(logging.DEBUG)\n\n# Configure a console output\nhandler = logging.StreamHandler(stream=sys.stdout)\nlogger.addHandler(handler)\n\n```\n\nSimilarly, `logging_enable` can enable detailed logging for a single operation,\neven when it isn't enabled for the client:\n\n```python\nservice_client.get_service_stats(logging_enable=True)\n```\n\n### Additional\n\nStill running into issues? If you encounter any bugs or have suggestions, please file an issue in the [Issues](<https://github.com/Azure/azure-sdk-for-python/issues>) section of the project.\n\n## Next steps\n\n### More sample code\n\nGet started with our [Maps Search samples](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/maps/azure-maps-search/samples) ([Async Version samples](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/maps/azure-maps-search/samples/async_samples)).\n\nSeveral Azure Maps Search Python SDK samples are available to you in the SDK's GitHub repository. These samples provide example code for additional scenarios commonly encountered while working with Maps Search\n\n```bash\nset AZURE_SUBSCRIPTION_KEY=\"<RealSubscriptionKey>\"\n\npip install azure-maps-search --pre\n\npython samples/sample_geocode.py\npython samples/sample_geocode_batch.py\npython samples/sample_get_polygon.py\npython samples/sample_reverse_geocode.py\npython samples/sample_reverse_geocode_batch.py\n```\n\n> Notes: `--pre` flag can be optionally added, it is to include pre-release and development versions for `pip install`. By default, `pip` only finds stable versions.\n\nFurther detail please refer to [Samples Introduction](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/maps/azure-maps-search/samples/README.md)\n\n### Additional documentation\n\nFor more extensive documentation on Azure Maps Search, see the [Azure Maps Search documentation](https://docs.microsoft.com/rest/api/maps/search) on docs.microsoft.com.\n\n## Contributing\n\nThis project welcomes contributions and suggestions.  Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit <https://cla.microsoft.com>.\n\nWhen you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.\n\nThis project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.\n\n<!-- LINKS -->\n[azure_subscription]: https://azure.microsoft.com/free/\n[azure_identity]: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/identity/azure-identity\n[azure_portal]: https://portal.azure.com\n[azure_cli]: https://docs.microsoft.com/cli/azure\n[azure-key-credential]: https://aka.ms/azsdk/python/core/azurekeycredential\n[default_azure_credential]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity#defaultazurecredential\n[register_microsoft_entra_id_app]: https://docs.microsoft.com/powershell/module/Az.Resources/New-AzADApplication?view=azps-8.0.0\n[maps_authentication_microsoft_entra_id]: https://docs.microsoft.com/azure/azure-maps/how-to-manage-authentication\n[create_new_application_registration]: https://portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/applicationsListBlade/quickStartType/AspNetWebAppQuickstartPage/sourceType/docs\n[manage_microsoft_entra_id_auth_page]: https://docs.microsoft.com/azure/azure-maps/how-to-manage-authentication\n[how_to_manage_authentication]: https://docs.microsoft.com/azure/azure-maps/how-to-manage-authentication#view-authentication-details\n\n\n# Release History\n\n## 2.0.0b2 (2024-12-12)\n\n### Features Added\n\n- Integrated support for SAS-based authentication\n\n## 2.0.0b1 (2024-08-06)\n\n### New Features and Enhancements\n\n- Support Search API `2023-06-01`\n\n- **Geocoding APIs**\n  - Introduced `get_geocoding` method to obtain longitude and latitude coordinates for a given address.\n  - Introduced `get_geocoding_batch` method to handle batch geocoding queries, supporting up to 100 queries in a single request.\n\n- **Reverse Geocoding APIs**\n  - Introduced `get_reverse_geocoding` method to get address details from given coordinates.\n  - Introduced `get_reverse_geocoding_batch` method to handle batch reverse geocoding queries, supporting up to 100 queries in a single request.\n\n- **Boundary APIs**\n  - Introduced `get_polygon` method to obtain polygon boundaries for a given set of coordinates with specified resolution and boundary result type.\n\n### Breaking Changes\n\n- **Removed Methods**\n  - Removed the `fuzzy_search` method.\n  - Removed the `search_point_of_interest` method.\n  - Removed the `search_address` method.\n  - Removed the `search_nearby_point_of_interest` method.\n  - Removed the `search_point_of_interest_category` method.\n  - Removed the `search_structured_address` method.\n  - Removed the `get_geometries` method.\n  - Removed the `get_point_of_interest_categories` method.\n  - Removed the `reverse_search_address` method.\n  - Removed the `reverse_search_cross_street_address` method.\n  - Removed the `search_inside_geometry` method.\n  - Removed the `search_along_route` method.\n  - Removed the `fuzzy_search_batch` method.\n  - Removed the `search_address_batch` method.\n\n## 1.0.0b3 (2024-05-15)\n \n### Bugs Fixed\n\n- Fix response validation error for reverse search address\n\n### Other Changes\n\n- Fix reverse search sample in README.md\n- Fix Sphinx errors\n- Fix pylint errors for pylint version 2.15.8\n\n## 1.0.0b2 (2022-10-11)\n\n### Other Changes\n\n- Update the tests using new test proxy\n- Update Doc strings\n\n## 1.0.0b1 (2022-09-06)\n\n- Initial Release\n",
    "bugtrack_url": null,
    "license": "MIT License",
    "summary": "Microsoft Azure Maps Search Client Library for Python",
    "version": "2.0.0b2",
    "project_urls": {
        "Homepage": "https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/maps/azure-maps-search"
    },
    "split_keywords": [
        "azure",
        " azure sdk"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "ecad0259ea647e1672eca97e474852a696415b1665461d15f73eed04fb6f9c97",
                "md5": "9a32fee67dc48e795ef018bec83c62cb",
                "sha256": "35fe557b493f3c47e2f355f5bcf99aecf7a86bad8ecf6338dd827c5407c2470e"
            },
            "downloads": -1,
            "filename": "azure_maps_search-2.0.0b2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "9a32fee67dc48e795ef018bec83c62cb",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 53997,
            "upload_time": "2024-12-12T00:31:42",
            "upload_time_iso_8601": "2024-12-12T00:31:42.827125Z",
            "url": "https://files.pythonhosted.org/packages/ec/ad/0259ea647e1672eca97e474852a696415b1665461d15f73eed04fb6f9c97/azure_maps_search-2.0.0b2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "3ffd6583db00209220e636786595eb5f505c0b2fead421ab01c6ef250a847a0d",
                "md5": "26088a4ac2124ab601d2452ae217533a",
                "sha256": "3ae32e5e95c23e5c091ca456929ce009877e83f01680f234fb6c54ac8ab613f3"
            },
            "downloads": -1,
            "filename": "azure_maps_search-2.0.0b2.tar.gz",
            "has_sig": false,
            "md5_digest": "26088a4ac2124ab601d2452ae217533a",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 56595,
            "upload_time": "2024-12-12T00:31:40",
            "upload_time_iso_8601": "2024-12-12T00:31:40.230549Z",
            "url": "https://files.pythonhosted.org/packages/3f/fd/6583db00209220e636786595eb5f505c0b2fead421ab01c6ef250a847a0d/azure_maps_search-2.0.0b2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-12-12 00:31:40",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "Azure",
    "github_project": "azure-sdk-for-python",
    "travis_ci": false,
    "coveralls": true,
    "github_actions": true,
    "lcname": "azure-maps-search"
}
        
Elapsed time: 2.91072s