How to get http status code | Python

Hi Team

I want to get status code while connecting to cluster.

from elasticsearch import Elasticsearch

client = Elasticsearch(
    "https://0.0.0.0.:9200",
    basic_auth=("elastic", "elastic"),
    verify_certs=False
)
print(client.status_code)
Traceback (most recent call last):
  File "connection.py", line 8, in <module>
    print(client.status_code)
AttributeError: 'Elasticsearch' object has no attribute 'status_code'

You need to connect to Elasticsearch to get a responde, setting up a client does nothing, just instantiate a client to be used when making requests to the cluster.

Also, I don't think the requests will return the status code.

If you want to check the connectivity with your cluster use something like this:

from elasticsearch import Elasticsearch

client = Elasticsearch(
    "https://localhost:9200",
    basic_auth=("elastic", "elastic"),
    verify_certs=False
)

resp = client.info()
print(resp)

You can also check some examples on how to use the python client here.

2 Likes

Additionally, when you have a response (like resp above), you can use resp.meta.status to get the status code. This is documented in Configuration | Elasticsearch Python Client [8.15] | Elastic.