> For the complete documentation index, see [llms.txt](https://valify.gitbook.io/documentation/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://valify.gitbook.io/documentation/apis/response-data-validation.md).

# Response Data Validation

***

You can validate the response data of all service APIs and its integrity through HMAC. With every successful Service API response, a header with key "hmac" contains the HMAC digest value. You can calculate the HMAC digest of the response body, and then compare it to the digest in the header.

### Calculation

#### Steps:

1. Sort the fields inside the "result" object by key in ascending alphabetical order (Lexicographical order)
2. Concatenate the ordered values into a single string (No separators)
3. Sort the fields inside the response body in lexicographical order.
4. Concatenate the ordered values into a single string (No separators)
5. Calculate the HMAC digest of the using SHA512 and the bundle’s HMAC key. HMAC Key will be provided separate from the documentation.
6. Convert the digest into Hexadecimal Lowercase format.
7. Compare the resulting digest with the one in the response header.

#### Example:

Consider the following response for the Egyptian National ID OCR:

```python
hmac_key = "secret_key"

response_data = {
  "result": {
    "back_nid": "back_nid",
    "date_of_birth": "date_of_birth",
    "expiry_date": "expiry_date",
    "gender": "gender",
    "husband_name": "husband_name",
    "marital_status": "marital_status",
    "profession": "profession",
    "release_date": "release_date",
    "religion": "religion",
    "area": "area",
    "first_name": "first_name",
    "front_nid": "front_nid",
    "full_name": "full_name",
    "serial_number": "serial_number",
    "street": "street"
  },
  "transaction_id": "transaction_id",
  "trials_remaining": 3,
}

concatenated_string = "areaback_niddate_of_birthexpiry_datefirst_namefront_nidfull_namegenderhusband_namemarital_statusprofessionrelease_datereligionserial_numberstreettransaction_id3"

calculated_digest = "d3f33383a5eae30125523bc8e6bdfbbe08cec2d87fb6f54e273e78faeec2fbc0f652d8e5f183729c3de405863018f9309f25b8000f3ca925d3efafdd4d4c0b70"
```

### Code Snippets

{% tabs %}
{% tab title="Python 3" %}

```python
import hashlib
import hmac
from collections import OrderedDict

def concatenate_dict(data_dict):
    od = OrderedDict(sorted(data_dict.items()))
    message = ''
    for _, v in od.items():
        if type(v) is dict:
            message += concatenate_dict(v)
        elif type(v) is bool:
            message += str(v).lower()
        elif v is None:
            message += 'null'
        else:
            message += str(v)

    return message

def calculate_digest(response_data, hmac_key):
    # Convert dict to string
    message = concatenate_dict(response_data)

    # Compute HMAC using SHA512
    calculated_hmac = hmac.new(
        hmac_key.encode('utf-8'),
        message.encode('utf-8'),
        hashlib.sha512
    ).hexdigest().lower()

    return calculated_hmac
    
response_data = {
    # Service API Response Data
}
hmac_key = "<hmac-key>"

print(calculate_digest(response_data, hmac_key))

```

{% endtab %}
{% endtabs %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://valify.gitbook.io/documentation/apis/response-data-validation.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
