Code Examples

Python and Javascript examples

The HDX DataStore API 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.

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

See Python specific examples per endpoint below.

Native Query

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

import requests

api_token = "API_TOKEN"  # Replace with your actual token
resource_id = "RESOURCE_ID" # Replace with actual resource id
url = "https://data.humdata.org/api/3/action/datastore_search"

params = {
    "resource_id": resource_id,
    "filters": {"country": "Kenya"},
    "limit": 5
}

headers = {
    "Authorization": api_token
}

# Native query: Get first 5 records where country is 'kenya'
response = requests.get(url, headers=headers, params=params)
data = response.json()

print("Total results:", data["result"]["total"])

SQL Query

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

import requests

api_token = "API_TOKEN"  # Replace with your actual token
resource_id = "RESOURCE_ID" # Replace with actual resource id
url = "https://data.humdata.org/api/3/action/datastore_search_sql"

# SQL query: Get first 5 records where country contains 'kenya'
sql = f'SELECT * FROM "{resource_id}" WHERE country ILIKE \'%kenya%\' LIMIT 5'

headers = {
    "Authorization": api_token
}

response = requests.get(url, headers=headers, params={"sql": sql})
data = response.json()

print("Total results returned:", len(data["result"]["records"]))

Last updated

Was this helpful?