def _get_error_code_from_api_exception(
    ex: APIExceptionLike,
) -> Optional[str]:
    """Returns api error code from ApiException.

    This is the "code" part from the failed api response. For example, a request failed
    with:

        HTTP response body: {
            "code": "MALFORMED_REQUEST",
            "error": "sampleId must match the following: \"/^[a-f0-9]{24}$/\"",
            "requestId": "a805582f5069db7696b9b66604873b3c"
        }

    will return "MALFORMED_REQUEST".
    """
    # TODO(Guarin, 03/23): Add debug log messages if ex.body has unexpected format once
    # we use process with spawn method.

    # Api error code exists only if returned body is json string.
    if not isinstance(ex.body, str):
        return None
    try:
        body = json.loads(ex.body)
    except JSONDecodeError:
        # Invalid json string.
        return None
    # We expect the api to return a json dict with a "code" entry.
    if isinstance(body, dict):
        return body.get("code")
    else:
        return None
Returns api error code from ApiException.

    This is the "code" part from the failed api response. For example, a request failed
    with:

        HTTP response body: {
            "code": "MALFORMED_REQUEST",
            "error": "sampleId must match the following: "/^[a-f0-9]{24}$/"",
            "requestId": "a805582f5069db7696b9b66604873b3c"
        }

    will return "MALFORMED_REQUEST".
    
lightly/api/retry_utils.py