# Code examples

The HDX Tabular Data endpoints can be used with many different coding languages and processes in the humanitarian sector. Be mindful of query limits and performance, especially when working with large datasets. See specific code examples below.&#x20;

Note that you can access the endpoints directly in your browser if you are signed in to HDX.

{% tabs %}
{% tab title="Python" %}
**See Python specific examples per endpoint below.**&#x20;

*These examples are tailored to the structure and field names of a specific resource, so when applying it to other resources, the filters and/or SQL will need to be adjusted to match their available columns and schema.*

#### Native query

This code searches an HDX resource where the location\_code field is exactly ‘AFG’, retrieves up to 5 results, and prints the total number of matches in the dataset.

```python
import requests

API_TOKEN = "API_TOKEN" # Replace with your actual token
RESOURCE_ID = "45036735-305b-42ae-9aef-b941d6dcb6d6"
URL = "https://data.humdata.org/api/3/action/datastore_search"


headers = {
    "Authorization": API_TOKEN,
    "Content-Type": "application/json"
}

response = requests.post(
    URL,
    headers=headers,
    json={
        "resource_id": RESOURCE_ID,
        "filters": {"location_code": "AFG"},
        "limit": 5
    }
).json()

# Native query: Get first 5 records where location is 'AFG'
print("Total results:", response["result"]["total"])
for record in response["result"]["records"]:
    print(record)
```

**SQL query**

This code runs a SQL query on an HDX resource to return the first 5 rows where the location\_field contains “AF” (case-insensitive search) and then prints how many rows were retrieved.

```python
import requests

API_TOKEN = "API_TOKEN" # Replace with your actual token
RESOURCE_ID = "45036735-305b-42ae-9aef-b941d6dcb6d6"
URL = "https://data.humdata.org/api/3/action/datastore_search_sql"

sql = f"""
SELECT location_code, sector_name, category, population_status, population,
       reference_period_start, reference_period_end
FROM "{RESOURCE_ID}"
WHERE location_code ILIKE '%AF%'
LIMIT 5
"""

headers = {
    "Authorization": API_TOKEN,
    "Content-Type": "application/json"
}

records = requests.post(URL, headers=headers, json={"sql": sql}) \
    .json().get("result", {}).get("records", [])

# SQL query: Get first 5 records where location contains 'AF'
print("Total results returned:", len(records))
for r in records:
    print(r)
```

{% endtab %}

{% tab title="Javascript" %}
**See Javascript specific examples per endpoint below.**

*These examples are tailored to the structure and field names of a specific resource, so when applying it to other resources, the filters and/or SQL will need to be adjusted to match their available columns and schema.*

#### Native Query

This code queries for rows in the given resource that contain the location code “AFG”, limits the returned rows to 5, and then logs the total number of matches across the dataset to the console.

```javascript
const RESOURCE_ID = "45036735-305b-42ae-9aef-b941d6dcb6d6";
const API_TOKEN = "API_TOKEN"; // Replace with your actual token
const URL = "https://data.humdata.org/api/3/action/datastore_search"

fetch(URL, {
  method: "POST",
  headers: {
    "Authorization": API_TOKEN,
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    resource_id: RESOURCE_ID,
    filters: { location_code: "AFG" },
    limit: 5
  })
})
  .then(res => res.json())
  .then(data => {
    console.log("Total results:", data.result.total)
    data.result.records.forEach(record => console.log(record))
  })
```

#### SQL Query

This code runs a SQL query to fetch up to 5 rows from the given resource where the location code contains “AF”, and then logs how many rows were returned.

```javascript
const RESOURCE_ID = "45036735-305b-42ae-9aef-b941d6dcb6d6";
const API_TOKEN = "API_TOKEN"; // Replace with your actual token
const URL = "https://data.humdata.org/api/3/action/datastore_search_sql"

const sql = `
SELECT location_code, sector_name, category, population_status, population,
       reference_period_start, reference_period_end
FROM "${RESOURCE_ID}"
WHERE location_code ILIKE '%AF%'
LIMIT 5
`

fetch(URL, {
  method: "POST",
  headers: {
    "Authorization": API_TOKEN,
    "Content-Type": "application/json"
  },
  body: JSON.stringify({ sql })
})
  .then(res => res.json())
  .then(data => {
    const records = (data.result && data.result.records) || []
    console.log("Total results returned:", records.length)
    records.forEach(r => console.log(r))
  })
```

{% endtab %}
{% endtabs %}


---

# Agent Instructions: 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://docs.humdata.org/build/hdx-apis/tabular-data-endpoints/code-examples.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.
