Skip to content
iscai-msft edited this page Mar 29, 2021 · 27 revisions

Python Low-Level Client

Our low-level clients provide simple, reliable connections to APIs for previews and advanced usage.

Here's how to get started:

>>> from azure.identity import DefaultAzureCredential
>>> from azure.example import ExampleClient
>>> from azure.example.rest import build_example_request
>>> client = ExampleClient(endpoint='https://www.example.org/', credential=DefaultAzureCredential())
>>> request = build_example_request()
>>> request
<HttpRequest [GET], url: 'https://www.example.org'>
>>> response = client.send_request(request)
>>> response
<HttpResponse: 200 OK, Content-Type: text/plain>
>>> response.raise_for_status()
>>> response.text
'Happy to see you!'

Code Snippets

Code snippets for how to use our Low-Level clients:

  1. Sync client
  2. Async client

What is a Low-Level Client

Our low-level clients provide simple, reliable connection to raw HTTP for previews and advanced usage. We provide caller send_request on the client to send requests to the service. Calls through this method fully harness the power of azure-core and azure-identity. We provide both synchronous and asynchronous low-level clients.

The basic structure of calls with low-level clients is:

  1. Initialize your client
  2. Create a request
  3. Send the request
  4. Handle the response

We will go into each step in the following sections

1. Initialize Your Client

First you import your client from the namespace of your package. For example, let's say your namespace is azure.example and your client's name is ExampleClient. Your import would look like

from azure.example import ExampleClient

Most clients require authenticating through their credential parameter. Depending on what authentication support your library is using, you can either authenticate-with-aad or authenticate with an AzureKeyCredential.

Additionally, most of our clients accept an endpoint parameter at initialization, usually a link to your own resource.

Authenticating with AAD

Depending on your library, our clients support authenticating with an Azure Active Directory (AAD) token credential. We always recommend using a credential type obtained from the azure-identity library for AAD authentication. For this example, we use the most common DefaultAzureCredential.

As an installation note, the azure-identity library is not a dependency of this library. Please pip install azure-identity before using AAD authentication

pip install azure-identity

The following code snippet shows you how to authenticate with a DefaultAzureCredential.

from azure.identity import DefaultAzureCredential
from azure.example import ExampleClient

client = ExampleClient(
    endpoint="https://www.example.org/",
    credential=DefaultAzureCredential()
)

Authenticating with AzureKeyCredential

Some libraries support authenticating with an AzureKeyCredential. The following code snippet shows you how to authenticate with an AzureKeyCredential

from azure.core.credentials import AzureKeyCredential
from azure.example import ExampleClient

credential = "myCredential"
client = ExampleClient(
    endpoint="https://www.example.org/",
    credential=AzureKeyCredential(credential)
)

2. Create a Request

Next, you need to create the request you want to be sent to the service.

We offer request builders to make creating your HttpRequests easier.

For more advanced users, you can also create your HttpRequest fully by yourself

Use our Request Builders

Our request builders:

  • Keep track of the URL and method of the call, so you don't have to
  • Let you know what parameters the service needs
  • Take care of formatting your parameters

These request builders are located in the rest folder of our libraries.

Now, let's make a request with a json body.

from azure.example.rest import build_json_request

request = build_json_request(
    json={"document": "Hello world!"},
    language="en",
)

Create Your Own HttpRequest

For more advanced scenarios, you can also create your own HttpRequest.

Let's make the same request as we do in our previous example

from azure.core.rest import HttpRequest

# this URL is relative to the endpoint we passed our client
request = HttpRequest("POST", "/helloWorld",
    json={"document": "Hello world!"},
    params={"language": "en"}
)

3. Send the Request

Now, we pass this request to your client's send_request method. This actually makes the network call.

from azure.example import ExampleClient

response = client.send_request(request) # makes the network call

4. Handle the Response

Our send_request call returns an HttpResponse.

Error handling

The response you get back from send_request will not automatically raise if your response is an error. If you wish to raise an error if your response is bad, call .raise_for_status() on your returned response.

try:
    response.raise_for_status()  # raises an error if your response is not good
except HttpResponseError as e:
    print(str(e))

JSON response

If the response you get back should be a json object, you can call .json() on your response to get it json-deserialized.

Putting this all together, see our code snippets for how you can deal with your response object

response = client.send_request(request)
try:
    response.raise_for_status()  # raises an error if your response is not good
    json_response = response.json()  # get your response as a json object
    # Now play with your JSON response!

except HttpResponseError as e:
    print(str(e))

Examples

Sync Client

from azure.identity import DefaultAzureCredential
from azure.example import ExampleClient
from azure.example.rest import build_json_request
from azure.core.exceptions import HttpResponseError

client = ExampleClient(
    endpoint="https://example.org",
    credential=DefaultAzureCredential()
)

request = build_json_request(
    json={"document": "Hello world!"},
    language="en",
)

response = client.send_request(request)

try:
    response.raise_for_status()
    json_response = response.json()
    # Play with your response!
except HttpResponseError:
    print(str(e))

Async Client

from azure.identity.aio import DefaultAzureCredential
from azure.example.aio import ExampleClient
from azure.example.rest import build_json_request
from azure.core.exceptions import HttpResponseError

request = build_json_request(
    json={"document": "Hello world!"},
    language="en",
)

with DefaultAzureCredential() as credential:
    with ExampleClient(endpoint="https://example.org", credential=credential) as client:
        response = await client.send_request(request)

        try:
            response.raise_for_status()
            await response.load_body()
            json_response = response.json()
            # Play with your response!
        except HttpResponseError:
            print(str(e))

Troubleshooting

Errors

All errors thrown by .raise_for_error() are exceptions defined in azure-core.

Logging

Our low-level clients also have logging support. They use the standard logging 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 un-redacted headers, can be enabled on a client with the logging_enable keyword argument.

from azure.identity import DefaultAzureCredential
from azure.example import ExampleClient

client = ExampleClient(
    endpoint="https://example.org",
    credential=DefaultAzureCredential(),
    logging_enable=True
)
Clone this wiki locally