elastic / elasticsearch-py

Official Python client for Elasticsearch
https://ela.st/es-python
Apache License 2.0
4.22k stars 1.18k forks source link

Update Documentation about catching Response Code in API Response Exception #2606

Closed bbullard916 closed 1 week ago

bbullard916 commented 3 months ago

Please update documentation to explain that in order the response code HTTP status code directly, you can do so only by catching the ApiResponse exception, which is raised when the API call is not successful. The ApiResponse exception contains the response object, which includes the status code.

Link to update information https://elasticsearch-py.readthedocs.io/en/v8.14.0/exceptions.html.

Example:

from elasticsearch import Elasticsearch, exceptions

es = Elasticsearch()

try:
    response = es.indices.put_mapping(index=index, body=mappings)
    if response.get('acknowledged'):
        # If the operation is successful, you can assume it's a 200 status code
        print("Mapping updated successfully. Status code: 200")
except exceptions.ApiResponse as e:
    # If there's an error, you can access the status code here
    print(f"Error updating mapping. Status code: {e.status_code}")
pquentin commented 3 months ago

Hey @bbullard916, thanks for opening this issue. A few things to note here:

  1. You don't have to assume it's a 200 status code, you can look in response.meta.status. I opened https://github.com/elastic/elastic-transport-python/pull/175 to document it. The idea then is that "Return type" in elasticsearch-py API docs will link to those docs.
  2. You should not assume it's a 200 status code! Indeed, 1/ the exists() API can return a 404, 2/ all 2xx codes are accepted, 3/ ignore_status allows you to change that behavior.
  3. exceptions.ApiResponse is not an exception, it's exceptions.ApiError. And we already document that you can reach status_code in that case: https://elasticsearch-py.readthedocs.io/en/v8.14.0/exceptions.html

Does that help?

bbullard916 commented 3 months ago

Thanks #1 will take care of the customers concern. He had problems trying to originally find an answer. Thanks for adding that.

pquentin commented 3 months ago

I have not managed to get Sphinx, our documentation system, to link to the transport docs yet.

pquentin commented 1 week ago

Closing as it is documented in https://www.elastic.co/guide/en/elasticsearch/client/python-api/current/config.html#_ignoring_status_codes at least.