---
mapped_pages:
  - https://www.elastic.co/guide/en/elasticsearch/client/python-api/current/connecting.html
---

# Connecting [connecting]

This page contains the information you need to connect the Client with {{es}}.


## Connecting to Elastic Cloud [connect-ec]

[Elastic Cloud](docs-content://deploy-manage/deploy/elastic-cloud/cloud-hosted.md) is the easiest way to get started with {{es}}. When connecting to Elastic Cloud with the Python {{es}} client you should always use the `cloud_id` parameter to connect. You can find this value within the "Manage Deployment" page after you’ve created a cluster (look in the top-left if you’re in Kibana).

We recommend using a Cloud ID whenever possible because your client will be automatically configured for optimal use with Elastic Cloud including HTTPS and HTTP compression.

::::{tab-set}
:group: sync_or_async

:::{tab-item} Standard Python
:sync: sync
```python
import os
from elasticsearch import Elasticsearch

# Password for the 'elastic' user generated by Elasticsearch
ELASTIC_PASSWORD = os.environ['ELASTIC_PASSWORD']

# Found in the 'Manage Deployment' page
CLOUD_ID = "deployment-name:dXMtZWFzdDQuZ2Nw..."

# Create the client instance
client = Elasticsearch(
    cloud_id=CLOUD_ID,
    basic_auth=("elastic", ELASTIC_PASSWORD)
)

# Successful response!
client.info()
# {'name': 'instance-0000000000', 'cluster_name': ...}
```
:::

:::{tab-item} Async Python
:sync: async
```python
import asyncio
import os
from elasticsearch import AsyncElasticsearch

# Password for the 'elastic' user generated by Elasticsearch
ELASTIC_PASSWORD = os.environ['ELASTIC_PASSWORD']

# Found in the 'Manage Deployment' page
CLOUD_ID = "deployment-name:dXMtZWFzdDQuZ2Nw..."

async def main():
    # Create the client instance
    client = AsyncElasticsearch(
        cloud_id=CLOUD_ID,
        basic_auth=("elastic", ELASTIC_PASSWORD)
    )

    # Successful response!
    await client.info()
    # {'name': 'instance-0000000000', 'cluster_name': ...}

asyncio.run(main())
```
:::

::::

## Connecting to a self-managed cluster [connect-self-managed-new]

By default {{es}} will start with security features like authentication and TLS enabled. To connect to the {{es}} cluster you’ll need to configure the Python {{es}} client to use HTTPS with the generated CA certificate in order to make requests successfully.

If you’re getting started with {{es}} we recommend reading the documentation on [configuring](docs-content://deploy-manage/deploy/self-managed/configure-elasticsearch.md) and [starting {{es}}](docs-content://deploy-manage/maintenance/start-stop-services/start-stop-elasticsearch.md) to ensure your cluster is running as expected.

When you start {{es}} for the first time you’ll see a distinct block like the one below in the output from {{es}} (you may have to scroll up if it’s been a while):

```sh
----------------------------------------------------------------
-> Elasticsearch security features have been automatically configured!
-> Authentication is enabled and cluster connections are encrypted.

->  Password for the elastic user (reset with `bin/elasticsearch-reset-password -u elastic`):
  lhQpLELkjkrawaBoaz0Q

->  HTTP CA certificate SHA-256 fingerprint:
  a52dd93511e8c6045e21f16654b77c9ee0f34aea26d9f40320b531c474676228
...
----------------------------------------------------------------
```

Note down the `elastic` user password and HTTP CA fingerprint for the next sections. In the examples below they will be stored in the variables `ELASTIC_PASSWORD` and `CERT_FINGERPRINT` respectively.

Depending on the circumstances there are two options for verifying the HTTPS connection, either verifying with the CA certificate itself or via the HTTP CA certificate fingerprint.


### Verifying HTTPS with CA certificates [_verifying_https_with_ca_certificates]

Using the `ca_certs` option is the default way the Python {{es}} client verifies an HTTPS connection.

The generated root CA certificate can be found in the `certs` directory in your {{es}} config location (`$ES_CONF_PATH/certs/http_ca.crt`). If you’re running {{es}} in Docker there is [additional documentation for retrieving the CA certificate](docs-content://deploy-manage/deploy/self-managed/install-elasticsearch-with-docker.md).

Once you have the `http_ca.crt` file somewhere accessible pass the path to the client via `ca_certs`:

::::{tab-set}
:group: sync_or_async

:::{tab-item} Standard Python
:sync: sync
```python
import os
from elasticsearch import Elasticsearch

# Password for the 'elastic' user generated by Elasticsearch
ELASTIC_PASSWORD = os.environ['ELASTIC_PASSWORD']

# Create the client instance
client = Elasticsearch(
    "https://localhost:9200",
    ca_certs="/path/to/http_ca.crt",
    basic_auth=("elastic", ELASTIC_PASSWORD)
)

# Successful response!
client.info()
# {'name': 'instance-0000000000', 'cluster_name': ...}
```
:::

:::{tab-item} Async Python
:sync: async
```python
import asyncio
import os
from elasticsearch import AsyncElasticsearch

# Password for the 'elastic' user generated by Elasticsearch
ELASTIC_PASSWORD = os.environ['ELASTIC_PASSWORD']

async def main():
    # Create the client instance
    client = AsyncElasticsearch(
        "https://localhost:9200",
        ca_certs="/path/to/http_ca.crt",
        basic_auth=("elastic", ELASTIC_PASSWORD)
    )

    # Successful response!
    await client.info()
    # {'name': 'instance-0000000000', 'cluster_name': ...}

asyncio.run(main())
```
:::

::::

::::{note}
If you don’t specify `ca_certs` or `ssl_assert_fingerprint` then the [certifi package](https://certifiio.readthedocs.io) will be used for `ca_certs` by default if available.
::::



### Verifying HTTPS with certificate fingerprints (Python 3.10 or later) [_verifying_https_with_certificate_fingerprints_python_3_10_or_later]

::::{note}
Using this method **requires using Python 3.10 or later** and isn’t available when using the `aiohttp` HTTP client library so can’t be used with `AsyncElasticsearch`.
::::


This method of verifying the HTTPS connection takes advantage of the certificate fingerprint value noted down earlier. Take this SHA256 fingerprint value and pass it to the Python {{es}} client via `ssl_assert_fingerprint`:

::::{tab-set}
:group: sync_or_async

:::{tab-item} Standard Python
:sync: sync
```python
import os
from elasticsearch import Elasticsearch

# Fingerprint either from Elasticsearch startup or above script.
# Colons and uppercase/lowercase don't matter when using
# the 'ssl_assert_fingerprint' parameter
CERT_FINGERPRINT = "A5:2D:D9:35:11:E8:C6:04:5E:21:F1:66:54:B7:7C:9E:E0:F3:4A:EA:26:D9:F4:03:20:B5:31:C4:74:67:62:28"

# Password for the 'elastic' user generated by Elasticsearch
ELASTIC_PASSWORD = os.environ['ELASTIC_PASSWORD']

client = Elasticsearch(
    "https://localhost:9200",
    ssl_assert_fingerprint=CERT_FINGERPRINT,
    basic_auth=("elastic", ELASTIC_PASSWORD)
)

# Successful response!
client.info()
# {'name': 'instance-0000000000', 'cluster_name': ...}
```
:::

:::{tab-item} Async Python
:sync: async
```python
import asyncio
import os
from elasticsearch import AsyncElasticsearch

# Fingerprint either from Elasticsearch startup or above script.
# Colons and uppercase/lowercase don't matter when using
# the 'ssl_assert_fingerprint' parameter
CERT_FINGERPRINT = "A5:2D:D9:35:11:E8:C6:04:5E:21:F1:66:54:B7:7C:9E:E0:F3:4A:EA:26:D9:F4:03:20:B5:31:C4:74:67:62:28"

# Password for the 'elastic' user generated by Elasticsearch
ELASTIC_PASSWORD = os.environ['ELASTIC_PASSWORD']

async def main():
    client = AsyncElasticsearch(
        "https://localhost:9200",
        ssl_assert_fingerprint=CERT_FINGERPRINT,
        basic_auth=("elastic", ELASTIC_PASSWORD)
    )

    # Successful response!
    await client.info()
    # {'name': 'instance-0000000000', 'cluster_name': ...}

asyncio.run(main())
```
:::

::::

The certificate fingerprint can be calculated using `openssl x509` with the certificate file:

```sh
openssl x509 -fingerprint -sha256 -noout -in /path/to/http_ca.crt
```

If you don’t have access to the generated CA file from {{es}} you can use the following script to output the root CA fingerprint of the {{es}} instance with `openssl s_client`:

```sh
# Replace the values of 'localhost' and '9200' to the
# corresponding host and port values for the cluster.
openssl s_client -connect localhost:9200 -servername localhost -showcerts </dev/null 2>/dev/null \
  | openssl x509 -fingerprint -sha256 -noout -in /dev/stdin
```

The output of `openssl x509` will look something like this:

```sh
SHA256 Fingerprint=A5:2D:D9:35:11:E8:C6:04:5E:21:F1:66:54:B7:7C:9E:E0:F3:4A:EA:26:D9:F4:03:20:B5:31:C4:74:67:62:28
```


## Connecting without security enabled [connect-no-security]

::::{warning}
Running {{es}} without security enabled is not recommended.
::::


If your cluster is configured with [security explicitly disabled](elasticsearch://reference/elasticsearch/configuration-reference/security-settings.md) then you can connect via HTTP:

::::{tab-set}
:group: sync_or_async

:::{tab-item} Standard Python
:sync: sync
```python
from elasticsearch import Elasticsearch

# Create the client instance
client = Elasticsearch("http://localhost:9200")

# Successful response!
client.info()
# {'name': 'instance-0000000000', 'cluster_name': ...}
```
:::

:::{tab-item} Async Python
:sync: async
```python
import asyncio
from elasticsearch import AsyncElasticsearch

async def main():
    # Create the client instance
    client = AsyncElasticsearch("http://localhost:9200")

    # Successful response!
    await client.info()
    # {'name': 'instance-0000000000', 'cluster_name': ...}

asyncio.run(main())
```
:::

::::

## Connecting to multiple nodes [connect-url]

The Python {{es}} client supports sending API requests to multiple nodes in the cluster. This means that work will be more evenly spread across the cluster instead of hammering the same node over and over with requests. To configure the client with multiple nodes you can pass a list of URLs, each URL will be used as a separate node in the pool.

::::{tab-set}
:group: sync_or_async

:::{tab-item} Standard Python
:sync: sync
```python
import os
from elasticsearch import Elasticsearch

# List of nodes to connect use with different hosts and ports.
NODES = [
    "https://localhost:9200",
    "https://localhost:9201",
    "https://localhost:9202",
]

# Password for the 'elastic' user generated by Elasticsearch
ELASTIC_PASSWORD = os.environ['ELASTIC_PASSWORD']

client = Elasticsearch(
    NODES,
    ca_certs="/path/to/http_ca.crt",
    basic_auth=("elastic", ELASTIC_PASSWORD)
)
```
:::

:::{tab-item} Async Python
:sync: async
```python
import os
from elasticsearch import AsyncElasticsearch

# List of nodes to connect use with different hosts and ports.
NODES = [
    "https://localhost:9200",
    "https://localhost:9201",
    "https://localhost:9202",
]

# Password for the 'elastic' user generated by Elasticsearch
ELASTIC_PASSWORD = os.environ['ELASTIC_PASSWORD']

client = AsyncElasticsearch(
    NODES,
    ca_certs="/path/to/http_ca.crt",
    basic_auth=("elastic", ELASTIC_PASSWORD)
)
```
:::

::::

By default nodes are selected using round-robin, but alternate node selection strategies can be configured with `node_selector_class` parameter.

::::{note}
If your {{es}} cluster is behind a load balancer like when using Elastic Cloud you won’t need to configure multiple nodes. Instead use the load balancer host and port.
::::



## Authentication [authentication]

This section contains code snippets to show you how to connect to various {{es}} providers. All authentication methods are supported on the client constructor or via the per-request `.options()` method:

::::{tab-set}
:group: sync_or_async

:::{tab-item} Standard Python
:sync: sync
```python
import os
from elasticsearch import Elasticsearch

# Authenticate from the constructor
client = Elasticsearch(
    "https://localhost:9200",
    ca_certs="/path/to/http_ca.crt",
    basic_auth=("username", os.environ["ELASTIC_PASSWORD"])
)

# Authenticate via the .options() method:
client.options(
    basic_auth=("username", os.environ["ELASTIC_PASSWORD"])
).indices.get(index="*")

# You can persist the authenticated client to use
# later or use for multiple API calls:
auth_client = client.options(api_key=os.environ["ELASTIC_API_KEY"])
for i in range(10):
    auth_client.index(
        index="example-index",
        document={"field": i}
    )
```
:::

:::{tab-item} Async Python
:sync: async
```python
import asyncio
import os
from elasticsearch import AsyncElasticsearch

async def main():
    # Authenticate from the constructor
    client = AsyncElasticsearch(
        "https://localhost:9200",
        ca_certs="/path/to/http_ca.crt",
        basic_auth=("username", os.environ["ELASTIC_PASSWORD"])
    )

    # Authenticate via the .options() method:
    await client.options(
        basic_auth=("username", os.environ["ELASTIC_PASSWORD"])
    ).indices.get(index="*")

    # You can persist the authenticated client to use
    # later or use for multiple API calls:
    auth_client = client.options(api_key=os.environ["ELASTIC_API_KEY"])
    for i in range(10):
        await auth_client.index(
            index="example-index",
            document={"field": i}
        )

asyncio.run(main())
```
:::

::::

### HTTP Basic authentication (Username and Password) [auth-basic]

HTTP Basic authentication uses the `basic_auth` parameter by passing in a username and password within a tuple:

::::{tab-set}
:group: sync_or_async

:::{tab-item} Standard Python
:sync: sync
```python
import os
from elasticsearch import Elasticsearch

# Adds the HTTP header 'Authorization: Basic <base64 username:password>'
client = Elasticsearch(
    "https://localhost:9200",
    ca_certs="/path/to/http_ca.crt",
    basic_auth=("username", os.environ["ELASTIC_PASSWORD"])
)
```
:::

:::{tab-item} Async Python
:sync: async
```python
import os
from elasticsearch import AsyncElasticsearch

# Adds the HTTP header 'Authorization: Basic <base64 username:password>'
client = AsyncElasticsearch(
    "https://localhost:9200",
    ca_certs="/path/to/http_ca.crt",
    basic_auth=("username", os.environ["ELASTIC_PASSWORD"])
)
```
:::

::::

### HTTP Bearer authentication [auth-bearer]

HTTP Bearer authentication uses the `bearer_auth` parameter by passing the token as a string. This authentication method is used by [Service Account Tokens](https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-security-create-service-token) and [Bearer Tokens](https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-security-get-token).

::::{tab-set}
:group: sync_or_async

:::{tab-item} Standard Python
:sync: sync
```python
import os
from elasticsearch import Elasticsearch

# Adds the HTTP header 'Authorization: Bearer token-value'
client = Elasticsearch(
    "https://localhost:9200",
    bearer_auth=os.environ["ELASTIC_TOKEN"]
)
```
:::

:::{tab-item} Async Python
:sync: async
```python
import os
from elasticsearch import AsyncElasticsearch

# Adds the HTTP header 'Authorization: Bearer token-value'
client = AsyncElasticsearch(
    "https://localhost:9200",
    bearer_auth=os.environ["ELASTIC_TOKEN"]
)
```
:::

::::

### API Key authentication [auth-apikey]

You can configure the client to use {{es}}'s API Key for connecting to your cluster. These can be generated through the [Elasticsearch Create API key API](https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-security-create-api-key) or [Kibana Stack Management](docs-content://deploy-manage/api-keys/elasticsearch-api-keys.md#create-api-key).

::::{tab-set}
:group: sync_or_async

:::{tab-item} Standard Python
:sync: sync
```python
from elasticsearch import Elasticsearch

# Adds the HTTP header 'Authorization: ApiKey <base64 api_key.id:api_key.api_key>'
client = Elasticsearch(
    "https://localhost:9200",
    ca_certs="/path/to/http_ca.crt",
    api_key=os.environ["ELASTIC_API_KEY"],
)
```
:::

:::{tab-item} Async Python
:sync: async
```python
from elasticsearch import AsyncElasticsearch

# Adds the HTTP header 'Authorization: ApiKey <base64 api_key.id:api_key.api_key>'
client = AsyncElasticsearch(
    "https://localhost:9200",
    ca_certs="/path/to/http_ca.crt",
    api_key=os.environ["ELASTIC_API_KEY"],
)
```
:::

::::

## Using the Client in a Function-as-a-Service Environment [connecting-faas]

This section illustrates the best practices for leveraging the {{es}} client in a Function-as-a-Service (FaaS) environment.

The most influential optimization is to initialize the client outside of the function, the global scope.

This practice does not only improve performance but also enables background functionality as – for example – [sniffing](https://www.elastic.co/blog/elasticsearch-sniffing-best-practices-what-when-why-how). The following examples provide a skeleton for the best practices.

::::{important}
The async client shouldn’t be used within Function-as-a-Service as a new event loop must be started for each invocation. Instead the synchronous `Elasticsearch` client is recommended.
::::



### GCP Cloud Functions [connecting-faas-gcp]

```python
import os
from elasticsearch import Elasticsearch

# Client initialization
client = Elasticsearch(
    cloud_id="deployment-name:ABCD...",
    api_key=os.environ["ELASTIC_API_KEY"]
)

def main(request):
    # Use the client
    client.search(index=..., query={"match_all": {}})
```

### AWS Lambda [connecting-faas-aws]

```python
import os
from elasticsearch import Elasticsearch

# Client initialization
client = Elasticsearch(
    cloud_id="deployment-name:ABCD...",
    api_key=os.environ["ELASTIC_API_KEY"]
)

def main(event, context):
    # Use the client
    client.search(index=..., query={"match_all": {}})
```

### Azure Functions [connecting-faas-azure]

```python
import azure.functions as func
import os
from elasticsearch import Elasticsearch

# Client initialization
client = Elasticsearch(
    cloud_id="deployment-name:ABCD...",
    api_key=os.environ["ELASTIC_API_KEY"]
)

def main(request: func.HttpRequest) -> func.HttpResponse:
    # Use the client
    client.search(index=..., query={"match_all": {}})
```

Resources used to assess these recommendations:

* [GCP Cloud Functions: Tips & Tricks](https://cloud.google.com/functions/docs/bestpractices/tips#use_global_variables_to_reuse_objects_in_future_invocations)
* [Best practices for working with AWS Lambda functions](https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html)
* [Azure Functions Python developer guide](https://docs.microsoft.com/en-us/azure/azure-functions/functions-reference-python?tabs=azurecli-linux%2Capplication-level#global-variables)
* [AWS Lambda: Comparing the effect of global scope](https://docs.aws.amazon.com/lambda/latest/operatorguide/global-scope.html)
