# Python SDK

Overview
The Sinch Python SDK was designed for developers. The SDK components are built with the specific language first and foremost in mind. After that, our focus was to keep the design simple for users that only want to leverage specific API calls they use but ensure customizability and future-proof access to other parts of our infrastructure.

The Python SDK has added common capabilities to further streamline the interaction with our platform:

- Simple HTTP component but allow users to override that with their own custom version if needed.
- Asynchronous support for all API calls, regardless of the original endpoint functionality.
- Automated token management/refresh code, so developers can use the system without micromanaging their authorization/authentication.


With all these common items, we hope to build out consistent frameworks with functionality all users require.

Another goal of ours while designing this new Python SDK was to mimic our REST APIs as much as possible, while still providing Pythonic developer experience.  We also use IDE type hints which, along with the REST API specification, allows the user to perform most API interactions without the need to use reference documentation.

Discoverability is one of the key components of great DX, hence Python SDK namespaces are small and specific yet descriptive.  For example:

```python
available_numbers = sinch_client.numbers.search_for_available_numbers(
    region_code="AR",
    number_type="LOCAL"
)
```

The main client class organizes the Sinch product portfolio (called domains within SDK) and its features into hierarchy that produces an API that is easy to read and discover:

![Python SDK example screenshot](/assets/pythonsdk.1d7a2de02d226ede8b8ecd39fcebebae0d7e4fe42bbb484372612cb9f0f46225.fd061bb8.jpg)

No third-party libraries are used by the Python SDK apart from industry standard Python HTTP libraries - requests and aiohttp.

Currently, Python versions: 3.9, 3.10, 3.11, 3.12 are supported. New stable versions will be added in the future, while older/EOL versions will be deprecated.

The Sinch Python SDK allows you to quickly interact with the  from inside your Python applications. When using the Python SDK, the code representing requests and queries sent to and responses received from the  are structured similarly to those that are sent and received using the .

Important Python SDK links:
The following links are available for your reference:

- [Sinch Python SDK repository](https://github.com/sinch/sinch-sdk-python)
- [Sinch Python SDK releases](https://github.com/sinch/sinch-sdk-python/releases)
- [Sinch Python SDK reference](https://developers.sinch.com/sdk/sinch-sdk-python/latest/index.html)


For previous Python SDK versions, click [here](/docs/sdks/python/sdk-reference-docs).

## Installation

The easiest way to install the SDK is using [`pip`](https://pypi.org/project/pip/):

1. Open a command prompt or terminal to the local repository folder.
2. Execute the following command:

```shell
pip install sinch
```


## Client

When using the Sinch Python SDK, you initialize communication with the Sinch backend by initializing the Python SDK's main client class. This client allows you to access the functionality of the Sinch Python SDK.

### Initialization

To start using the SDK, you need to initialize the main client class with your credentials from your Sinch [dashboard](https://dashboard.sinch.com).

```python
from sinch import SinchClient

sinch_client = SinchClient(key_id="key_id", key_secret="key_secret", project_id="YOUR_project_id")
```

Note
For testing purposes on your local environment it's fine to use hardcoded values, but before deploying to production we strongly recommend using environment variables to store the credentials, as in the following example:

```python
import os
from sinch import SinchClient

sinch_client = SinchClient(
    key_id=os.getenv("KEY_ID"),
    key_secret=os.getenv("KEY_SECRET"),
    project_id=os.getenv("PROJECT_ID")
)
```

Setting the region
You must set `conversation_region` before using the Conversation API, either in the `SinchClient(...)` constructor or on `sinch_client.configuration` before the first Conversation API call, as in the following example:

```python
from sinch import SinchClient

sinch_client = SinchClient(
    project_id="your-project-id",
    key_id="your-key-id",
    key_secret="your-key-secret",
    conversation_region="eu",
)

# Note: The conversation_region can also be set through the configuration object,

# but you must ensure this setting is done BEFORE any Conversation API call:

sinch_client.configuration.conversation_region = "eu"
```

## Domains

The Python SDK currently supports the following products:

Conversation
Numbers
Number Lookup
Voice v2
SMS (standalone)
### Numbers Domain

Note:
This guide describes the syntactical structure of the Python SDK for the Numbers API, including any differences that may exist between the API itself and the SDK. For a full reference on Numbers API calls and responses, see the [Numbers API Reference](/docs/numbers/api-reference/numbers).

The code sample on this page is an example of how to use the Python SDK to list the available numbers given a set of constraints. We've also provided an example that accomplishes the same task using the REST API.

SDK
list_numbers.py
```python list_numbers.py
"""
Sinch Python Snippet

This snippet is available at https://github.com/sinch/sinch-sdk-python/tree/main/examples/snippets
"""

import os
from dotenv import load_dotenv
from sinch import SinchClient

load_dotenv()

sinch_client = SinchClient(
    project_id=os.environ.get("SINCH_PROJECT_ID") or "MY_PROJECT_ID",
    key_id=os.environ.get("SINCH_KEY_ID") or "MY_KEY_ID",
    key_secret=os.environ.get("SINCH_KEY_SECRET") or "MY_KEY_SECRET"
)

available_numbers = sinch_client.numbers.search_for_available_numbers(
    region_code="AR",
    number_type="LOCAL"
)

print("Available numbers to rent:\n")
for number in available_numbers.iterator():
    print(number)
```

REST API
```Json

import requests

project_id = "YOUR_project_id"
url = "https://numbers.api.sinch.com/v1/projects/" + project_id + "/availableNumbers"

query = {
  "regionCode": "US",
  "type": "LOCAL"
}

response = requests.get(url, params=query, auth=('<username>','<password>'))

data = response.json()
print(data)
```

The Sinch Python SDK organizes different functionalities in the Sinch product suite into domains. These domains are accessible through the client. For example, `sinch_client.numbers.[endpoint_category].[method]`. You can also create a domain-specific client from a general client. For example:

```Python

from sinch import SinchClient

sinch_client = SinchClient(key_id="YOUR_key_id", key_secret="YOUR_key_secret",
project_id="YOUR_project_id")

from sinch.domains.numbers import Numbers

numbers_client = Numbers(sinch_client)
```

In the Sinch Python SDK, Numbers API endpoints are accessible through the client (either a general client or a Numbers-specific client).

- `numbers`
- `numbers.regions`
- `numbers.event_destinations`


For example:

```Python

numbers_available = sinch_client.numbers.search_for_available_numbers(
    region_code="US",
    number_type="LOCAL"
)
```

The `numbers` category of the Python SDK corresponds to the [available-numbers](/docs/numbers/api-reference/numbers/available-number/) and [active-numbers](/docs/numbers/api-reference/numbers/active-number/) endpoints. The mapping between the API operations and corresponding Python methods are described below:

| API operation | SDK method |
|  --- | --- |
| [Rent the first available number matching the provided criteria](/docs/numbers/api-reference/numbers/available-number/numberservice_rentanynumber) | `rent_any` |
| [Activate a new phone number](/docs/numbers/api-reference/numbers/available-number/numberservice_rentnumber) | `rent` |
| [Check availability](/docs/numbers/api-reference/numbers/available-number/numberservice_getavailablenumber) | `check_availability` |
| [Search for available phone numbers](/docs/numbers/api-reference/numbers/available-number/numberservice_listavailablenumbers) | `search_for_available_numbers` |
| [List active numbers for a project](/docs/numbers/api-reference/numbers/active-number/numberservice_listactivenumbers) | `list` |
| [Update active number](/docs/numbers/api-reference/numbers/active-number/numberservice_updateactivenumber) | `update` |
| [Retrieve active number](/docs/numbers/api-reference/numbers/active-number/numberservice_getactivenumber) | `get` |
| [Release active number](/docs/numbers/api-reference/numbers/active-number/numberservice_releasenumber) | `release` |


The `numbers.regions` category of the Python SDK corresponds to the [available-regions](/docs/numbers/api-reference/numbers/available-regions/) endpoint. The mapping between the API operations and corresponding Python methods are described below:

| API operation | SDK method |
|  --- | --- |
| [List available regions](/docs/numbers/api-reference/numbers/available-regions/) | `list` |


The `numbers.event_destinations` category of the Python SDK corresponds to the [numbers-callbacks](/docs/numbers/api-reference/numbers/numbers-callbacks) endpoint. The mapping between the API operations and corresponding Python methods are described below:

| API operation | SDK method |
|  --- | --- |
| [Get callbacks configuration](/docs/numbers/api-reference/numbers/numbers-callbacks/getcallbackconfiguration) | `get` |
| [Update callbacks configuration](/docs/numbers/api-reference/numbers/numbers-callbacks/updatecallbackconfiguration) | `update` |


Requests and queries made using the Python SDK are similar to those made using the Numbers API. Many of the fields are named and structured similarly. For example, consider the representations of a Numbers API region code. One field is represented in JSON, and the other is using our Python SDK:

SDK
```Python
region_code = "US"
```

REST API
```JSON
"regionCode": "US"
```

Note that the fields are nearly the same. Additionally, path parameters, request body parameters, and query parameters that are used in the API are all passed as arguments to the corresponding Python method.

When translating field names from the Numbers API to the Python SDK, remember that many of the API field names are in **camelCase**, whereas the Python SDK field names are in **snake_case**. This pattern change manages almost all field name translations between the API and the SDK.

Below is a table detailing field names present in the Numbers API and their modified counterparts in the Numbers API Python SDK:

| API field name | SDK field name |
|  --- | --- |
| `regionCode` | `region_code` |
| `type` | `number_type` |
| `types` | `number_types` |
| `numberPattern.pattern` | `number_pattern` |
| `numberPattern.searchPattern` | `number_search_pattern` |
| `phoneNumber` | `phone_number` |
| `smsConfiguration` | `sms_configuration` |
| `capability` | `capabilities` |


When making calls directly to the API, we use JSON objects, including (in some cases) nested JSON objects. When using the Python SDK, we use dictionaries instead of nested JSON objects. For example, consider the sms configuration objects below. One is represented in JSON, the other as a Python dictionary:

SDK
```Python
sms_configuration = {
    "servicePlanId": "service_plan_string"
}
```

{
```JSON
"smsConfiguration": {
    "servicePlanId": "service_plan_string"
}
```

Note that, in both cases, the `servicePlanId` object is structured in exactly the same way as they would be in a normal Python call to the Numbers API. When using the Python SDK, any argument that represents a nested JSON object will be represented as a Python dictionary at the top level, but the contents of that dictionary must be represented as JSON objects.

Response fields match the API responses. They are delivered as Python objects, with each top-level field represented as a property. Note that any nested objects normally returned by the Numbers API are returned as dictionaries by the Python SDK. Additionally, if there are any responses that differ significantly from the API responses, we note them in the endpoint category documentation.

### Number Lookup Domain

Note:
This guide describes the syntactical structure of the Python SDK for the Number Lookup API, including any differences that may exist between the API itself and the SDK. For a full reference on Number Lookup API calls and responses, see the [Number Lookup API Reference](/docs/number-lookup-api-v2/api-reference/number-lookup-v2).

The code sample on this page is an example of how to use the Python SDK to look up a phone number. We've also provided an example that accomplishes the same task using the REST API.

SDK
snippet.py
```python snippet.py
"""
Sinch Python Snippet

This snippet is available at https://github.com/sinch/sinch-sdk-python/tree/main/examples/snippets
"""

import os
from dotenv import load_dotenv
from sinch import SinchClient

load_dotenv()

sinch_client = SinchClient(
    project_id=os.environ.get("SINCH_PROJECT_ID") or "MY_PROJECT_ID",
    key_id=os.environ.get("SINCH_KEY_ID") or "MY_KEY_ID",
    key_secret=os.environ.get("SINCH_KEY_SECRET") or "MY_KEY_SECRET",
)

# The phone number to look up in E.164 format (e.g. +1234567890)
phone_number = "PHONE_NUMBER"

response = sinch_client.number_lookup.lookup(number=phone_number)

print(f"Number lookup result:\n{response}")
```

REST API
```Json

import requests

key = "YOUR_access_key"
secret = "YOUR_access_secret"
project_id = "YOUR_project_id"
number = "YOUR_phone_number"
url = "https://lookup.api.sinch.com/v2/projects/" + project_id + "/lookups"

def lookup(num):
    payload = {
        "number": num
    }

    headers = {
        "Content-Type": "application/json"
    }

    response = requests.post(url, json=payload, headers=headers, auth=(key, secret))

    data = response.json()
    print(data)

lookup(number)
```

The Sinch Python SDK organizes different functionalities in the Sinch product suite into domains. These domains are accessible through the client. For example, `sinch_client.number_lookup.[endpoint_category].[method]`. You can also create a domain-specific client from a general client. For example:

```Python

from sinch import SinchClient

sinch_client = SinchClient(key_id="YOUR_key_id", key_secret="YOUR_key_secret",
project_id="YOUR_project_id")

from sinch.domains.number_lookup import NumberLookup

number_lookup_client = NumberLookup(sinch_client)
```

In the Sinch Python SDK, Number Lookup API endpoints are accessible through the client (either a general client or a Number Lookup-specific client). The naming convention of the endpoint's representation in the SDK matches the API:

- `lookup`


For example:

```Python

lookup_number = sinch_client.number_lookup.lookup(number="YOUR_PHONE_NUMBER")
```

The `lookup` category of the Python SDK corresponds to the [lookup](/docs/number-lookup-api-v2/api-reference/number-lookup-v2/numberlookupv2/) endpoint. The mapping between the API operations and corresponding Python methods are described below:

| API operation | SDK method |
|  --- | --- |
| [Look up a phone number](/docs/number-lookup-api-v2/api-reference/number-lookup-v2/numberlookupv2/numberlookupv2_lookup) | `lookup` |


Requests and queries made using the Python SDK are similar to those made using the Number Lookup API. Many of the fields are named and structured similarly. For example, consider the representations of a Number Lookup API region code. One field is represented in JSON, and the other is using our Python SDK:

SDK
```Python
mobile_country_code = "310"
```

REST API
```JSON
"mobileCountryCode": "310"
```

Note that the fields are nearly the same. Additionally, path parameters, request body parameters, and query parameters that are used in the API are all passed as arguments to the corresponding Python method.

When translating field names from the Number Lookup API to the Python SDK, remember that many of the API field names are in **camelCase**, whereas the Python SDK field names are in **snake_case**. This pattern change manages almost all field name translations between the API and the SDK.

Below is a table detailing field names present in the Number Lookup API and their modified counterparts in the Number Lookup API Python SDK:

| API field name | SDK field name |
|  --- | --- |
| `regionCode` | `region_code` |
| `type` | `number_type` |
| `types` | `number_types` |
| `mobileCountryCode` | `mobile_country_code` |
| `swapPeriod` | `swap_period` |
| `phoneNumber` | `phone_number` |
| `portingDate` | `porting_date` |


Response fields match the API responses. They are delivered as Python objects, with each top-level field represented as a property. Note that any nested objects normally returned by the Number Lookup API are returned as dictionaries by the Python SDK. Additionally, if there are any responses that differ significantly from the API responses, we note them in the endpoint category documentation.

### Conversation Domain

Note:
This guide describes the syntactical structure of the Python SDK for the Conversation API, including any differences that may exist between the API itself and the SDK. For a full reference on Conversation API calls and responses, see the [Conversation API Reference](/docs/conversation/api-reference/conversation).

The code sample below is an example of how to use the Python SDK to send an SMS text message. The Conversation API call that accomplishes the same task is displayed below for reference.

SDK
send-message.py
```python send-message.py
"""
Sinch Python Snippet

This snippet is available at https://github.com/sinch/sinch-sdk-python/tree/main/examples/snippets
"""

import os
from dotenv import load_dotenv
from sinch import SinchClient

load_dotenv()

sinch_client = SinchClient(
    project_id=os.environ.get("SINCH_PROJECT_ID") or "MY_PROJECT_ID",
    key_id=os.environ.get("SINCH_KEY_ID") or "MY_KEY_ID",
    key_secret=os.environ.get("SINCH_KEY_SECRET") or "MY_KEY_SECRET",
    conversation_region=os.environ.get("SINCH_CONVERSATION_REGION") or "MY_CONVERSATION_REGION"
)

# The ID of the Conversation App to send the message from
app_id = "CONVERSATION_APP_ID"
# The phone number of the recipient in E.164 format (e.g. +46701234567)
recipient_identities = [
    {
        "channel": "SMS",
        "identity": "RECIPIENT_PHONE_NUMBER"
    }
]

response = sinch_client.conversation.messages.send_text_message(
    app_id=app_id,
    text="[Python SDK: Conversation] Sample text message",
    recipient_identities=recipient_identities
)

print(f"Successfully sent text message.\n{response}")
```

REST API
```Json

import requests
import base64

appId = "YOUR_app_id"
accessKey = "YOUR_key_id"
accessSecret = "YOUR_key_secret"
projectId = "YOUR_project_id"
channel = "SMS"
identity = "RECIPIENT_number"
sender = "YOUR_sms_sender"
url = "https://us.conversation.api.sinch.com/v1/projects/" + projectId + "/messages:send"

data = accessKey + ":" + accessSecret
encodedBytes = base64.b64encode(data.encode("utf-8"))
accessToken = str(encodedBytes, "utf-8")

payload = {
  "app_id": appId,
  "recipient": {
      "identified_by": {
          "channel_identities": [
            {
                "channel": channel,
                "identity": identity
            }  
            ]
      }
  },
  "message": {
      "text_message": {
          "text": "Text message from Sinch Conversation API."
      }
  },
  "channel_properties": {
    "SMS_SENDER": sender
  }  
}

headers = {
  "Content-Type": "application/json",
  "Authorization": "Basic " + accessToken
}

response = requests.post(url, json=payload, headers=headers)

data = response.json()
print(data)
```

The Sinch Python SDK organizes different functionalities in the Sinch product suite into domains. These domains are accessible through the client. For example, `sinch_client.conversation.[endpoint_category].[method]`. You can also create a domain-specific client from a general client. For example:

```Python

from sinch import SinchClient

sinch_client = SinchClient(key_id="YOUR_key_id", key_secret="YOUR_key_secret",
project_id="YOUR_project_id")

from sinch.domains.conversation import Conversation

conversation_client = Conversation(sinch_client)
```

In the Sinch Python SDK, Conversation API endpoints are accessible through the client (either a general client or a Conversation-specific client). The naming convention of the endpoint's representation in the SDK matches the API:

- `conversation.apps`
- `conversation.capability`
- `conversation.consents`
- `conversation.contacts`
- `conversation.conversations`
- `conversation.event_destinations`
- `conversation.events`
- `conversation.messages`
- `conversation.project_settings`
- `conversation.templates`
- `conversation.transcoding`


To validate and parse incoming events, use `conversation.sinch_events()`. For more information, see [Sinch Events](#sinch-events).

For example:

```Python

app_id = "CONVERSATION_APP_ID"
recipient_identities = [
    {
        "channel": "SMS",
        "identity": "RECIPIENT_PHONE_NUMBER"
    }
]

response = sinch_client.conversation.messages.send_text_message(
    app_id=app_id,
    text="[Python SDK: Conversation] Sample text message",
    recipient_identities=recipient_identities
)
```

The `conversation.apps` category of the Python SDK corresponds to the [apps](/docs/conversation/api-reference/conversation/app/) endpoint. The mapping between the API operations and corresponding Python methods are described below:

| API operation | SDK method |
|  --- | --- |
| [List all apps for a given project](/docs/conversation/api-reference/conversation/app/app_listapps) | `list` |
| [Create an app](/docs/conversation/api-reference/conversation/app/app_createapp) | `create` |
| [Get an app](/docs/conversation/api-reference/conversation/app/app_getapp) | `get` |
| [Update an app](/docs/conversation/api-reference/conversation/app/app_updateapp) | `update` |
| [Delete an app](/docs/conversation/api-reference/conversation/app/app_deleteapp) | `delete` |


The `conversation.capability` category of the Python SDK corresponds to the [capability](/docs/conversation/api-reference/conversation/capability/) endpoint. The mapping between the API operations and corresponding Python methods are described below:

| API operation | SDK method |
|  --- | --- |
| [Capability lookup](/docs/conversation/api-reference/conversation/capability/capability_querycapability) | `lookup` |


The `conversation.consents` category of the Python SDK corresponds to the [consent](/docs/conversation/api-reference/conversation/consent/) endpoint. The mapping between the API operations and corresponding Python methods are described below:

| API operation | SDK method |
|  --- | --- |
| [Get identities from consent list](/docs/conversation/api-reference/conversation/consent/consents_getconsents) | `list_identities` |
| [Get audit records from consent lists](/docs/conversation/api-reference/conversation/consent/consents_getconsentsauditrecords) | `list_audit_records` |


The `conversation.contacts` category of the Python SDK corresponds to the [contacts](/docs/conversation/api-reference/conversation/contact/) endpoint. The mapping between the API operations and corresponding Python methods are described below:

| API operation | SDK method |
|  --- | --- |
| [List contacts](/docs/conversation/api-reference/conversation/contact/contact_listcontacts) | `list` |
| [Create a contact](/docs/conversation/api-reference/conversation/contact/contact_createcontact) | `create` |
| [Get a contact](/docs/conversation/api-reference/conversation/contact/contact_getcontact) | `get` |
| [Update a contact](/docs/conversation/api-reference/conversation/contact/contact_updatecontact) | `update` |
| [Delete a contact](/docs/conversation/api-reference/conversation/contact/contact_deletecontact) | `delete` |
| [Merge two contacts](/docs/conversation/api-reference/conversation/contact/contact_mergecontact) | `merge_contact` |
| [Get channel profile](/docs/conversation/api-reference/conversation/contact/contact_getchannelprofile) | `get_channel_profile` |
| [List contact identity conflicts](/docs/conversation/api-reference/conversation/contact/contact_listidentityconflicts) | `list_identity_conflicts` |


Additionally, there are two helper methods for getting a channel profile:

| API operation | SDK method |
|  --- | --- |
| [Get channel profile by contact ID](/docs/conversation/api-reference/conversation/contact/contact_getchannelprofile) | `get_channel_profile_by_contact_id` |
| [Get channel profile by channel identity](/docs/conversation/api-reference/conversation/contact/contact_getchannelprofile) | `get_channel_profile_by_channel_identity` |


The `conversation.conversations` category of the Python SDK corresponds to the [conversations](/docs/conversation/api-reference/conversation/conversation/) endpoint. The mapping between the API operations and corresponding Python methods are described below:

| API operation | SDK method |
|  --- | --- |
| [List conversations](/docs/conversation/api-reference/conversation/conversation/conversation_listconversations) | `list` |
| [Create a conversation](/docs/conversation/api-reference/conversation/conversation/conversation_createconversation) | `create` |
| [Get a conversation](/docs/conversation/api-reference/conversation/conversation/conversation_getconversation) | `get` |
| [Update a conversation](/docs/conversation/api-reference/conversation/conversation/conversation_updateconversation) | `update` |
| [Delete a conversation](/docs/conversation/api-reference/conversation/conversation/conversation_deleteconversation) | `delete` |
| [List recent conversations](/docs/conversation/api-reference/conversation/conversation/conversation_listrecentconversations) | `list_recent` |
| [Stop an active conversation](/docs/conversation/api-reference/conversation/conversation/conversation_stopactiveconversation) | `stop_active` |
| [Inject a message](/docs/conversation/api-reference/conversation/conversation/conversation_injectmessage) | `inject_message` |
| [Inject an event](/docs/conversation/api-reference/conversation/conversation/events_injectevent) | `inject_event` |


The `conversation.event_destinations` category of the Python SDK corresponds to the [webhooks](/docs/conversation/api-reference/conversation/webhooks/) endpoint. The mapping between the API operations and corresponding Python methods are described below:

| API operation | SDK method |
|  --- | --- |
| [List webhooks](/docs/conversation/api-reference/conversation/webhooks/webhooks_listwebhooks) | `list` |
| [Create a new webhook](/docs/conversation/api-reference/conversation/webhooks/webhooks_createwebhook) | `create` |
| [Get a webhook](/docs/conversation/api-reference/conversation/webhooks/webhooks_getwebhook) | `get` |
| [Update an existing webhook](/docs/conversation/api-reference/conversation/webhooks/webhooks_updatewebhook) | `update` |
| [Delete an existing webhook](/docs/conversation/api-reference/conversation/webhooks/webhooks_deletewebhook) | `delete` |


The `conversation.events` category of the Python SDK corresponds to the [events](/docs/conversation/api-reference/conversation/events/) endpoint. The mapping between the API operations and corresponding Python methods are described below:

| API operation | SDK method |
|  --- | --- |
| [Send an event](/docs/conversation/api-reference/conversation/events/events_sendevent) | `send` |


The `conversation.messages` category of the Python SDK corresponds to the [messages](/docs/conversation/api-reference/conversation/messages/) endpoint. The mapping between the API operations and corresponding Python methods are described below:

| API operation | SDK method |
|  --- | --- |
| [Send a message](/docs/conversation/api-reference/conversation/messages/messages_sendmessage) | `send` |
| [Get a message](/docs/conversation/api-reference/conversation/messages/messages_getmessage) | `get` |
| [Delete a message](/docs/conversation/api-reference/conversation/messages/messages_deletemessage) | `delete` |
| [List messages](/docs/conversation/api-reference/conversation/messages/messages_listmessages) | `list` |
| [Update message metadata](/docs/conversation/api-reference/conversation/messages/messages_updatemessagemetadata) | `update` |
| [List messages by channel identity](/docs/conversation/api-reference/conversation/messages/messages_listmessagesbychannelidentity) | `list_last_messages_by_channel_identity` |


Additionally, there are several helper methods for sending messages of the different media types:

| API operation | SDK method |
|  --- | --- |
| [Send a card message](https://developers.sinch.com/docs/conversation/api-reference/conversation/messages/messages_sendmessage#messages/messages_sendmessage/t=request&path=message) | `send_card_message` |
| [Send a carousel message](https://developers.sinch.com/docs/conversation/api-reference/conversation/messages/messages_sendmessage#messages/messages_sendmessage/t=request&path=message) | `send_carousel_message` |
| [Send a choice message](https://developers.sinch.com/docs/conversation/api-reference/conversation/messages/messages_sendmessage#messages/messages_sendmessage/t=request&path=message) | `send_choice_message` |
| [Send a contact info message](https://developers.sinch.com/docs/conversation/api-reference/conversation/messages/messages_sendmessage#messages/messages_sendmessage/t=request&path=message) | `send_contact_info_message` |
| [Send a list message](https://developers.sinch.com/docs/conversation/api-reference/conversation/messages/messages_sendmessage#messages/messages_sendmessage/t=request&path=message) | `send_list_message` |
| [Send a location message](https://developers.sinch.com/docs/conversation/api-reference/conversation/messages/messages_sendmessage#messages/messages_sendmessage/t=request&path=message) | `send_location_message` |
| [Send a media message](https://developers.sinch.com/docs/conversation/api-reference/conversation/messages/messages_sendmessage#messages/messages_sendmessage/t=request&path=message) | `send_media_message` |
| [Send a template message](https://developers.sinch.com/docs/conversation/api-reference/conversation/messages/messages_sendmessage#messages/messages_sendmessage/t=request&path=message) | `send_template_message` |
| [Send a text message](https://developers.sinch.com/docs/conversation/api-reference/conversation/messages/messages_sendmessage#messages/messages_sendmessage/t=request&path=message) | `send_text_message` |


The `conversation.project_settings` category of the Python SDK corresponds to the [project settings](/docs/conversation/api-reference/conversation/project-settings/) endpoint. The mapping between the API operations and corresponding Python methods are described below:

| API operation | SDK method |
|  --- | --- |
| [Create project settings](/docs/conversation/api-reference/conversation/project-settings/projectsettings_createsettings) | `create` |
| [Get project settings](/docs/conversation/api-reference/conversation/project-settings/projectsettings_getsettings) | `get` |
| [Update project settings](/docs/conversation/api-reference/conversation/project-settings/projectsettings_updatesettings) | `update` |
| [Delete project settings](/docs/conversation/api-reference/conversation/project-settings/projectsettings_deletesettings) | `delete` |


The `conversation.templates` category of the Python SDK corresponds to the [Templates V2](/docs/conversation/api-reference/template/templates-v2/) endpoint. The mapping between the API operations and corresponding Python methods are described below:

| API operation | SDK method |
|  --- | --- |
| [List templates](/docs/conversation/api-reference/template/templates-v2/templates_v2_listtemplates) | `list` |
| [Create a template](/docs/conversation/api-reference/template/templates-v2/templates_v2_createtemplate) | `create` |
| [Get a template](/docs/conversation/api-reference/template/templates-v2/templates_v2_gettemplate) | `get` |
| [Update a template](/docs/conversation/api-reference/template/templates-v2/templates_v2_updatetemplate) | `update` |
| [Delete a template](/docs/conversation/api-reference/template/templates-v2/templates_v2_deletetemplate) | `delete` |
| [List translations for a template](/docs/conversation/api-reference/template/templates-v2/templates_v2_listtranslations) | `list_translations` |


The `conversation.transcoding` category of the Python SDK corresponds to the [transcoding](/docs/conversation/api-reference/conversation/transcoding/) endpoint. The mapping between the API operations and corresponding Python methods are described below:

| API operation | SDK method |
|  --- | --- |
| [Transcode a message](/docs/conversation/api-reference/conversation/transcoding/transcoding_transcodemessage) | `transcode_message` |


The `conversation.sinch_events()` method returns a handler for the events that the Conversation API sends to your event destination. Pass the secret configured for your event destination to validate signatures:

| Operation | SDK method |
|  --- | --- |
| Validate the event signature | `validate_authentication_header` |
| Parse an event into a typed model | `parse_event` |


For example:

```Python

sinch_events_service = sinch_client.conversation.sinch_events("YOUR_callback_secret")

if not sinch_events_service.validate_authentication_header(
    headers=headers,
    json_payload=raw_body,
):
    # Reject the request
    ...

event = sinch_events_service.parse_event(raw_body, headers)
```

Requests and queries made using the Python SDK are similar to those made using the Conversation API. Many of the fields are named and structured similarly. In most cases, they are the same. For example, consider the representations of a Conversation API app ID below. One field is represented in JSON, and the other is using our Python SDK:

SDK
```Python
app_id = "{APP_ID}"
```

REST API
```JSON
"app_id": "{APP_ID}"
```

Note that the fields have the same name. Additionally, path parameters, request body parameters, and query parameters that are used in the API are all passed as arguments to the corresponding python method. For example, consider this example in which the `get` method of the `messages` category is invoked:

SDK
```Python

conversation_response = sinch_client.conversation.messages.get(
                    message_id="YOUR_message_id",
                    messages_source="CONVERSATION_SOURCE")
```

REST API
```JSON

url = "https://us.conversation.api.sinch.com/v1/projects/" + project_id + "/messages/" + YOUR_message_id

payload = {
    "messages_source": "CONVERSATION_SOURCE"
}
```

When using the Conversation API, `message_id` would be included as a path parameter, and `messages_source` would be included as a query parameter in the JSON payload. With the Python SDK, both parameters are included as arguments in the `get` method.

For `update` methods, the SDK builds the `update_mask` from the arguments you pass. Arguments you omit are left unchanged on the server. Passing `None` explicitly clears the field.

The SDK uses the same field names as the Conversation API, with one exception. `from` is a reserved word in Python, so the SDK uses `from_`:

| API field name | SDK field name |
|  --- | --- |
| `from` | `from_` |


When making calls directly to the API, we use JSON objects, including (in some cases) nested JSON objects. When using the Python SDK, we use dictionaries instead of nested JSON objects. For example, consider the message objects below. One is represented in JSON, the other as a Python dictionary:

SDK
```Python
message = {
    "text_message": {
        "text": "Text message from Sinch Conversation API."
    }
}
```

REST API
```JSON
"message": {
    "text_message": {
        "text": "Text message from Sinch Conversation API."
    }
}
```

Note that, in both cases, the `text_message` and `text` objects are structured in exactly the same way as they would be in a normal Python call to the Conversation API. When using the Python SDK, any argument that represents a nested JSON object will be represented as a Python dictionary at the top level, but the contents of that dictionary must be represented as JSON objects. This is also highlighted in the below example:

SDK
```Python

recipient={
    "identified_by" : {
        "channel_identities" : [
            {"identity":"RECIPIENT_number","channel" : "SMS"}
        ]
    }
}
```

REST API
```JSON

"recipient": {
    "identified_by": {
        "channel_identities": [
            {"identity":"RECIPIENT_number","channel" : "SMS"}  
        ]
    }
}
```

Response fields match the API responses. They are delivered as typed Python objects (Pydantic models), with each field, including nested objects, represented as a property.

### SMS Domain (existing integrations only) 

End of sale: standalone SMS REST API
The SMS domain calls the standalone SMS REST API, which reached end of sale on 15 April 2026 and is no longer available to new customers. All new SMS integrations must use the [Conversation domain](#conversation-domain) with the [SMS channel of Conversation API](/docs/conversation/channel-support/sms/). Use the SMS domain only to maintain an existing integration.

Show the SMS domain reference (standalone SMS REST API, existing integrations only)
**Client setup for the SMS domain**

Existing standalone SMS REST API integrations in **Australia (AU)**, **Brazil (BR)**, **Canada (CA)**, **the United States (US)**, and **the European Union (EU)** can authenticate with project credentials or with a service plan ID and API token. You must set `sms_region` before the first SMS API call:

```python
# Standalone SMS REST API: existing integrations only (end of sale 15 April 2026). For new integrations, use the SMS channel of Conversation API: https://developers.sinch.com/docs/conversation/channel-support/sms/
from sinch import SinchClient

# Using Project auth

sinch_client = SinchClient(
    project_id="your-project-id",
    key_id="your-key-id",
    key_secret="your-key-secret",
    sms_region="eu",
)

# Or using SMS token auth

token_client = SinchClient(
    service_plan_id="your-service-plan-id",
    sms_api_token="your-sms-api-token",
    sms_region="us",
)

# Note: The code is backward compatible. The sms_region can still be set through the configuration object,

# but you must ensure this setting is done BEFORE any SMS API call:

sinch_client.configuration.sms_region = "eu"
```

Note:
This guide describes the syntactical structure of the Python SDK for the standalone SMS REST API (existing integrations only), including any differences that may exist between the API itself and the SDK. For a full reference on SMS API calls and responses, see the [standalone SMS API reference](/docs/sms/api-reference/).

For existing standalone SMS REST API integrations, the code sample below shows how to send a message with the Python SDK. For new integrations, send SMS with the Conversation domain instead. We've also provided an example that accomplishes the same task using the REST API.

SDK
send-message.py
```python send-message.py
# Standalone SMS REST API: existing integrations only (end of sale 15 April 2026). For new integrations, use the SMS channel of Conversation API: https://developers.sinch.com/docs/conversation/channel-support/sms/
"""
Sinch Python Snippet

This snippet is available at https://github.com/sinch/sinch-sdk-python/tree/main/examples/snippets
"""

import os
from dotenv import load_dotenv
from sinch import SinchClient

load_dotenv()

sinch_client = SinchClient(
    project_id=os.environ.get("SINCH_PROJECT_ID") or "MY_PROJECT_ID",
    key_id=os.environ.get("SINCH_KEY_ID") or "MY_KEY_ID",
    key_secret=os.environ.get("SINCH_KEY_SECRET") or "MY_KEY_SECRET",
    sms_region=os.environ.get("SINCH_SMS_REGION") or "MY_SMS_REGION"
)

response = sinch_client.sms.batches.send_sms(
    to=["+1234567890"],
    from_="+2345678901",
    body="Hello, this is a test message!"
)

print(f"Batch sent:\n{response}")
```

REST API
```Json

import requests

servicePlanId = "YOUR_service_plan_id"
apiToken = "YOUR_api_token"
sinchNumber = "YOUR_Sinch_number"
toNumber = "YOUR_recipient_number"
url = "https://us.sms.api.sinch.com/xms/v1/" + servicePlanId + "/batches"

payload = {
  "from": sinchNumber,
  "to": [
    toNumber
  ],
  "body": "Hello from Sinch!"
}

headers = {
  "Content-Type": "application/json",
  "Authorization": "Bearer " + apiToken
}

response = requests.post(url, json=payload, headers=headers)

data = response.json()
print(data)
```

The Sinch Python SDK organizes different functionalities in the Sinch product suite into domains. These domains are accessible through the client. For example, `sinch_client.sms.[endpoint_category].[method]`. You can also create a domain-specific client from a general client. For example:

```Python

from sinch import SinchClient

sinch_client = SinchClient(key_id="YOUR_key_id", key_secret="YOUR_key_secret",
project_id="YOUR_project_id")

from sinch.domains.sms import SMS

SMS_client = SMS(sinch_client)
```

In the Sinch Python SDK, SMS API endpoints are accessible through the client (either a general client or a SMS-specific client). The naming convention of the endpoint's representation in the SDK matches the API:

- `sms.batches`
- `sms.delivery_reports`
- `sms.sinch_events`
- `sms.groups`
- `sms.inbounds`


For example:

```Python
send_batch_response = sinch_client.sms.batches.send(
    body = "Hello from Sinch!",
    to = ["YOUR_to_number"],
    from_ = "YOUR_Sinch_number",
    delivery_report = "none"
)
```

The `sms.batches` category of the Python SDK corresponds to the [batches](/docs/sms/api-reference/sms/batches/) endpoint. The mapping between the API operations and corresponding Python methods are described below:

| API operation | SDK method |
|  --- | --- |
| [Send an SMS](/docs/sms/api-reference/sms/batches/sendsms) | `send_sms` |
| [Send an MMS](/docs/sms/api-reference/sms/batches/sendsms) | `send_mms` |
| [Send a binary message](/docs/sms/api-reference/sms/batches/sendsms) | `send_binary` |
| [List batches](/docs/sms/api-reference/sms/batches/listbatches) | `list` |
| [Dry run an SMS](/docs/sms/api-reference/sms/batches/dry_run) | `dry_run_sms` |
| [Dry run an MMS](/docs/sms/api-reference/sms/batches/dry_run) | `dry_run_mms` |
| [Dry run a binary message](/docs/sms/api-reference/sms/batches/dry_run) | `dry_run_binary` |
| [Get a batch message](/docs/sms/api-reference/sms/batches/getbatchmessage) | `get` |
| [Update a batch SMS](/docs/sms/api-reference/sms/batches/updatebatchmessage) | `update_sms` |
| [Update a batch MMS](/docs/sms/api-reference/sms/batches/updatebatchmessage) | `update_mms` |
| [Update a batch binary message](/docs/sms/api-reference/sms/batches/updatebatchmessage) | `update_binary` |
| [Replace an SMS batch](/docs/sms/api-reference/sms/batches/replacebatch) | `replace_sms` |
| [Replace an MMS batch](/docs/sms/api-reference/sms/batches/replacebatch) | `replace_mms` |
| [Replace a binary batch](/docs/sms/api-reference/sms/batches/replacebatch) | `replace_binary` |
| [Cancel a batch message](/docs/sms/api-reference/sms/batches/cancelbatchmessage) | `cancel` |
| [Send delivery feedback for a message](/docs/sms/api-reference/sms/batches/deliveryfeedback) | `send_delivery_feedback` |


The `delivery_reports` category of the Python SDK corresponds to the [delivery_report and delivery_reports](/docs/sms/api-reference/sms/delivery-reports/) endpoints. The mapping between the API operations and corresponding Python methods are described below:

| API operation | SDK method |
|  --- | --- |
| [Retrieve a delivery report](/docs/sms/api-reference/sms/delivery-reports/getdeliveryreportbybatchid) | `get` |
| [Retrieve a recipient delivery report](/docs/sms/api-reference/sms/delivery-reports/getdeliveryreportbyphonenumber) | `get_for_number` |
| [Retrieve a list of delivery reports](/docs/sms/api-reference/sms/delivery-reports/getdeliveryreports) | `list` |


The `groups` category of the Python SDK corresponds to the [groups](/docs/sms/api-reference/sms/groups/) endpoints. The mapping between the API operations and corresponding Python methods are described below:

| API operation | SDK method |
|  --- | --- |
| [Retrieve a group](/docs/sms/api-reference/sms/groups/retrievegroup) | `get` |
| [Replace a group](/docs/sms/api-reference/sms/groups/replacegroup) | `replace` |
| [Update a group](/docs/sms/api-reference/sms/groups/updategroup) | `update` |
| [Delete a group](/docs/sms/api-reference/sms/groups/deletegroup) | `delete` |
| [List groups](/docs/sms/api-reference/sms/groups/listgroups) | `list` |
| [Create a group](/docs/sms/api-reference/sms/groups/creategroup) | `create` |
| [Get phone numbers for a group](/docs/sms/api-reference/sms/groups/getmembers) | `list_members` |


The `inbounds` category of the Python SDK corresponds to the [inbounds](/docs/sms/api-reference/sms/inbounds/) endpoints. The mapping between the API operations and corresponding Python methods are described below:

| API operation | SDK method |
|  --- | --- |
| [Retrieve an inbound message](/docs/sms/api-reference/sms/inbounds/retrieveinboundmessage) | `get` |
| [List incoming messages](/docs/sms/api-reference/sms/inbounds/listinboundmessages) | `list` |


The `sms.sinch_events` category of the Python SDK contains methods for webhook signature validation.

| API operation | SDK method |
|  --- | --- |
| Validate signature | `_validate_signature` |
| Validate authentication header | `validate_authentication_header` |
| Parse event | `parse_event` |


Note:
Note that the `service_plan_id` path parameter does not need to be included in any requests created by the Python SDK.

Requests and queries made using the Python SDK are similar to those made using the SMS API. Many of the fields are named and structured similarly. In most cases, they are the same. For example, consider the representations of a SMS API app ID below. One field is represented in JSON, and the other is using our Python SDK:

SDK
```Python
batch_id = "{BATCH_ID}"
```

REST API
```JSON
"batch_id": "{BATCH_ID}"
```

Note that the fields have the same name. Additionally, path parameters, request body parameters, and query parameters that are used in the API are all passed as arguments to the corresponding python method. For example, consider this example in which the `get` method of the `batch` class is invoked:

SDK
```Python

SMS_response = sinch_client.sms.batches.get("01GR4H81QVX78E06F8ETGQ1CZK")
```

REST API
```JSON

url = "https://us.SMS.api.sinch.com/v1/" + service_plan_id + "/batches/" + batch_id
```

When using the SMS API, `service_plan_id` and `batch_id` would be included as path parameters in the JSON payload. With the Python SDK, the `batch_id` parameter is included as an argument in the `get` method.

Below is a table detailing field names present in the SMS API and their modified counterparts in the SMS API Python SDK:

| API field name | SDK field name |
|  --- | --- |
| `type` | `type_` |
| `from` | `from_` |
| `recipient_msisdn` | `recipient_number` |


When making calls directly to the API, we use JSON objects, including (in some cases) nested JSON objects. When using the Python SDK, we use dictionaries instead of nested JSON objects.

Response fields match the API responses. They are delivered as Python objects, with each top-level field represented as a property. Note that any nested objects normally returned by the SMS API are returned as dictionaries by the Python SDK.

Note:
Any field labelled `from` in the API is labelled as `from_` in the Python SDK.

### Voice v2 Domain

Note:
This guide describes the syntactical structure of the Python SDK for the Voice v2 API, including any differences that may exist between the API itself and the SDK. For a full reference on Voice v2 API calls and responses, see the [Voice v2 API Reference](/docs/voice-2.0/api-reference/voice).

The code sample below is an example of how to use the Python SDK to to make a text to speech phone call to a phone number. We've also provided an example that accomplishes the same task using the REST API.

SDK
snippet.py
```python snippet.py
"""
Sinch Python Snippet

This snippet is available at https://github.com/sinch/sinch-sdk-python/tree/main/examples/snippets
"""

import os

from dotenv import load_dotenv

from sinch import SinchClient
from sinch.domains.voice.helpers.v2.svaml import (
    Calls,
    CommandsSequenceCreator,
)

load_dotenv()

sinch_client = SinchClient(
    project_id=os.environ.get("SINCH_PROJECT_ID") or "MY_PROJECT_ID",
    key_id=os.environ.get("SINCH_KEY_ID") or "MY_KEY_ID",
    key_secret=os.environ.get("SINCH_KEY_SECRET") or "MY_KEY_SECRET",
)

# The phone number to be used as the caller ID, in E.164 format (e.g., +12025550123)
sinch_phone_number = (
    os.environ.get("SINCH_PHONE_NUMBER") or "MY_SINCH_PHONE_NUMBER"
)

# The phone number you want to call, in E.164 format (e.g., +12025550123)
recipient_phone_number = "RECIPIENT_PHONE_NUMBER"

# The SVAML commands describing the call flow: dial out to the recipient
commands = CommandsSequenceCreator().dial(
    recipient_phone_number,
    from_=sinch_phone_number,
    name="Python_SDK_Snippet_Call",
    on_answer=CommandsSequenceCreator().text(
        "Hello, your call is now connected.",
        "Emma",
        on_finish=Calls.hangup(),
    ),
)

response = sinch_client.voice.v2.calls.start(commands=commands)

print(f"Call Successfully started.\n{response}")
```

REST API
```python
import requests

project_id = "YOUR_projectId_PARAMETER"
url = "https://voice.api.sinch.com/v2/projects/" + project_id + "/calls"

query = {
  "serviceId": "6e124178-c29d-46a5-943c-5c2ae544aade"
}

payload = {
  "commands": [
    {
      "command": "dial",
      "callName": "origin",
      "from": {
        "type": "PHONE",
        "phone": {
          "number": "+15551234567"
        }
      },
      "to": {
        "type": "PHONE",
        "phone": {
          "number": "+15559876543"
        }
      },
      "dialTimeoutDurationSeconds": 30,
      "maxCallDurationSeconds": 3600,
      "events": {
        "onAnswer": [
          {
            "command": "messages",
            "messages": [
              {
                "type": "SAY",
                "say": {
                  "text": "Hello, your call is now connected.",
                  "voiceName": "Emma"
                }
              }
            ]
          }
        ],
        "onHangup": [
          {
            "command": "hangup"
          }
        ]
      }
    }
  ]
}

headers = {
  "Content-Type": "application/json",
  "Idempotency-Key": "stringstringstri"
}

response = requests.post(url, json=payload, headers=headers, params=query, auth=('<username>','<password>'))

data = response.json()
print(data)
```

The Sinch Python SDK organizes different functionalities in the Sinch product suite into domains. These domains are accessible through the client. For example, `sinch_client.voice.v2.[endpoint_category].[method]`. You can also create a domain-specific client from a general client. For example:

```Python

from sinch import SinchClient
from sinch.domains.voice.v2 import Voice

sinch_client = SinchClient(key_id="YOUR_key_id", key_secret="YOUR_key_secret",
project_id="YOUR_project_id")

voice_client = Voice(sinch_client)
```

In the Sinch Python SDK, Voice v2 API endpoints are accessible through the client (either a general client or a Voice-specific client). The naming convention of the endpoint's representation in the SDK matches the API:

- [`voice.v2.batches`![external](/assets/external-blue.5a59beb5e5a442f78b530509ddf6b5d0fa705285ff8181e59adf96b5c2c73e25.33310b29.svg)](https://developers.sinch.com/sdk/sinch-sdk-python/latest/api/sinch.domains.voice.api.v2.batches_apis.html)
- [`voice.v2.calls`![external](/assets/external-blue.5a59beb5e5a442f78b530509ddf6b5d0fa705285ff8181e59adf96b5c2c73e25.33310b29.svg)](https://developers.sinch.com/sdk/sinch-sdk-python/latest/api/sinch.domains.voice.api.v2.calls_apis.html)
- [`voice.v2.services`![external](/assets/external-blue.5a59beb5e5a442f78b530509ddf6b5d0fa705285ff8181e59adf96b5c2c73e25.33310b29.svg)](https://developers.sinch.com/sdk/sinch-sdk-python/latest/api/sinch.domains.voice.api.v2.services_apis.html)
- [`voice.v2.sessions`![external](/assets/external-blue.5a59beb5e5a442f78b530509ddf6b5d0fa705285ff8181e59adf96b5c2c73e25.33310b29.svg)](https://developers.sinch.com/sdk/sinch-sdk-python/latest/api/sinch.domains.voice.api.v2.sessions_apis.html)
- [`voice.v2.sinch_events`![external](/assets/external-blue.5a59beb5e5a442f78b530509ddf6b5d0fa705285ff8181e59adf96b5c2c73e25.33310b29.svg)](https://developers.sinch.com/sdk/sinch-sdk-python/latest/api/sinch.domains.voice.api.v2.sinch_events.html)
- [`voice.v2.svaml`![external](/assets/external-blue.5a59beb5e5a442f78b530509ddf6b5d0fa705285ff8181e59adf96b5c2c73e25.33310b29.svg)](https://developers.sinch.com/sdk/sinch-sdk-python/latest/api/sinch.domains.voice.api.v2.svaml_apis.html)


For example:

```Python
commands = CommandsSequenceCreator().dial(
    recipient_phone_number,
    from_=sinch_phone_number,
    name="Python_SDK_Snippet_Call",
    on_answer=CommandsSequenceCreator().text(
        "Hello, your call is now connected.",
        "Emma",
        on_finish=Calls.hangup(),
    ),
)

response = sinch_client.voice.v2.calls.start(commands=commands)
```

Requests and queries made using the Python SDK are similar to those made using the Voice v2 API. Many of the fields are named and structured similarly.

When translating field names from the Voice v2 API to the Python SDK, remember that many of the API field names are in **camelCase**, whereas the Python SDK field names are in **snake_case**. This pattern change manages almost all field name translations between the API and the SDK.

When making calls directly to the API, we use JSON objects, including (in some cases) nested JSON objects. When using the Python SDK, we use dictionaries instead of nested JSON objects. For example, consider the callout `from` configuration objects below. One is represented in JSON, the other as a Python dictionary:

SDK
```python
"from_": {"type": "PHONE", "phone": {"number": from_phone_number}}
```

JSON
```JSON
"from": {
    "type": "PHONE",
    "phone": {
        "number": "YOUR_phone_number"
    }
}
```

Note that, in both cases, the `from` object is structured in exactly the same way as they would be in a normal Python call to the Voice v2 API. When using the Python SDK, any argument that represents a nested JSON object will be represented as a Python dictionary at the top level, but the contents of that dictionary must be represented as JSON objects.

Response fields match the API responses. They are delivered as Python objects, with each top-level field represented as a property. Note that any nested objects normally returned by the Voice v2 API are returned as dictionaries by the Python SDK. Additionally, if there are any responses that differ significantly from the API responses, we note them in the endpoint category documentation.

## SDK features

### Calling any Sinch API with the HTTP client

The Sinch Python SDK provides a low-level HTTP client, exposed as `sinch.http`, to call the endpoints that the SDK doesn't cover yet, or the APIs that have no SDK support at all.

When using the HTTP client, the SDK still handles:

- the authentication, from the credentials of your `SinchClient`;
- the retries of rate-limited (HTTP 429) responses;
- the client settings, such as the timeout.


The HTTP client is available from version 2.5.0.

#### When to use it

Use `sinch.http` when:

- the endpoint you need isn't available in the SDK yet.
- you want to try a new or beta API without waiting for an SDK release.


For endpoints already supported by the SDK, use their dedicated methods instead, such as `sinch.numbers.list()`, which validate your input and return typed models.

#### Getting started

The HTTP client uses the authentication configured in `SinchClient`, so you can initialize the Sinch client as usual.

```python
from sinch import SinchClient

sinch = SinchClient(
    project_id="YOUR_project_id",
    key_id="YOUR_access_key_id",
    key_secret="YOUR_access_key_secret",
)
```

Then call the method matching the HTTP verb, with the absolute URL of the endpoint:

```python
response = sinch.http.get(
    f"https://example.api.sinch.com/v1/projects/{project_id}/resources",
    query_params="status=active&pageSize=5",
)

print(response.status)
resources = response.content.as_json()
```

The URL and the query string are sent as you provide them. The URL is not validated, path segments are not encoded, and the only change to the query string is a leading `?`, added when it is missing.

The following methods are available:

| Method | Description |
|  --- | --- |
| `get(url, ...)` | Sends a GET request. |
| `delete(url, ...)` | Sends a DELETE request. |
| `post(url, body=None, ...)` | Sends a POST request, with an optional body. |
| `put(url, body=None, ...)` | Sends a PUT request, with an optional body. |
| `patch(url, body=None, ...)` | Sends a PATCH request, with an optional body. |
| `post_form_data(url, form_params, ...)` | Sends a POST request with a `multipart/form-data` body, to upload files. |


All of them also accept the following keyword arguments:

| Argument | Description |
|  --- | --- |
| `query_params` | The query string, already URL-encoded. The leading `?` is optional. |
| `headers` | The request headers, as a dictionary or as a list of `(name, value)` pairs to repeat a header. |
| `options` | A `RequestOptions` object that overrides the client settings for this request only. See [Request options](#request-options). |


#### Authentication

The authentication configured in the `SinchClient` is added by default to the requests of the HTTP client. When several credentials are configured, the SDK uses the first one available in this order.

1. OAuth2, when `key_id` and `key_secret` are set. The access token is requested on the first call, cached and renewed when it expires.
2. The SMS API token, when `service_plan_id` and `sms_api_token` are set.


Since the project ID is part of the URL you build, it isn't required by the HTTP client.

To call an endpoint with a different authentication, disable the SDK authentication and set your own header:

```python
from sinch.core.clients.request_options import RequestOptions

response = sinch.http.get(
    "https://example.api.sinch.com/v1/resource",
    headers={"Authorization": "Bearer YOUR_token"},
    options=RequestOptions(use_sinch_auth=False),
)
```

#### Sending a request body

You can send the body in two ways.

**Let the SDK encode it.** Use one of the body classes from `sinch.core.models.http_body`. The SDK encodes the body and sets the `Content-Type` header for you:

| Class | Content-Type |
|  --- | --- |
| `JsonBody(data)` | `application/json` |
| `UrlEncodedBody(fields)` | `application/x-www-form-urlencoded` |
| `MultipartBody(fields)` | `multipart/form-data` |
| `FilePart(content, filename=None, content_type=None)` | The media type of the file, guessed from its name if not provided |


```python
from sinch.core.models.http_body import JsonBody

response = sinch.http.post(
    f"https://example.api.sinch.com/v1/projects/{project_id}/resources",
    body=JsonBody({"name": "My resource", "status": "active"}),
)
```

**Encode it yourself.** Pass a `str` or `bytes` body and set the `Content-Type` header yourself. Bytes are sent untouched, and a string is encoded with the charset of the `Content-Type` header (UTF-8 by default). The SDK raises a `ValidationException` if the header is missing.

```python
response = sinch.http.post(
    f"https://example.api.sinch.com/v1/projects/{project_id}/resources",
    body='{"name": "My resource"}',
    headers={"Content-Type": "application/json"},
)
```

##### Uploading files

`post_form_data` sends a `multipart/form-data` request. Each value can be a text value, a `FilePart` or a list of them to repeat the field:

```python
from pathlib import Path

from sinch.core.models.http_body import FilePart

response = sinch.http.post_form_data(
    "https://example.api.sinch.com/v1/uploads",
    form_params={
        "description": "Monthly report",
        "file": FilePart(Path("report.pdf")),
    },
)
```

#### Request options

`RequestOptions` (from `sinch.core.clients.request_options`) overrides the client settings for a single request. Any option you don't set keeps the value of the client.

| Option | Description | Default |
|  --- | --- | --- |
| `use_sinch_auth` | `False` sends the request without the SDK authentication. | `True` |
| `timeout_seconds` | Timeout of the request in seconds. `0` disables it. | `10` |
| `retry_configuration` | A `RetryConfiguration` replacing the retry settings of the client for this request. | `RetryPolicy.DEFAULT`, up to 3 retries |


The defaults are the values used when neither the client nor `RequestOptions` are set.

```python
from sinch.core.clients.request_options import RequestOptions
from sinch.core.clients.retry_configuration import RetryConfiguration
from sinch.core.enums import RetryPolicy

response = sinch.http.get(
    f"https://example.api.sinch.com/v1/projects/{project_id}/resources",
    options=RequestOptions(
        timeout_seconds=30,
        retry_configuration=RetryConfiguration(retry_policy=RetryPolicy.NONE),
    ),
)
```

#### Reading the response

Each method returns an `HTTPResponse` with:

- `status`: the HTTP status code.
- `headers`: the response headers. Header names are case-insensitive, and `get_all(name)` returns every value of a repeated header.
- `content`: the response body, readable with one of the methods below.


| Method | Description | Example |
|  --- | --- | --- |
| `as_json()` | Returns the body parsed as JSON, or `None` if the body is empty. | resources = response.content.as_json()print(resources["items"]) |
| `as_string()` | Returns the body decoded with the charset of the `Content-Type` header, or UTF-8 if it declares none. | text = response.content.as_string()print(text) |
| `as_bytes()` | Returns the body as received, without decoding. | data = response.content.as_bytes()Path("report.pdf").write_bytes(data) |


#### Handling errors

A response with a status code of 400 or above raises an `HttpException` (from `sinch.domains.http.api.v1.exceptions`). The full response is still available in its `http_response` attribute:

```python
from sinch.domains.http.api.v1.exceptions import HttpException

try:
    response = sinch.http.get(url)
except HttpException as error:
    print(error.response_status_code)
    print(error.http_response.content.as_string())
```