> For the complete documentation index, see [llms.txt](https://docs.humdata.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.humdata.org/build/hdx-apis/hapi/examples-and-use-cases.md).

# Examples and use-cases

These examples show common tasks in Python. The full documentation at hdx-hapi.readthedocs.io has the same patterns in JavaScript, Node.js, and R. In every example, replace {your app identifier} with the identifier you generated in How to query HAPI.

**A note on pagination.** Queries are capped at 10,000 rows. Larger results are silently truncated to the first 10,000 with no warning, and a higher `limit` just returns a `422`. Page through anything you don't know to be small: request pages until one comes back shorter than your page size.&#x20;

### 1. Who is doing what where

List the organizations active in a country by querying operational presence. This example returns operational presence for Afghanistan. Add a sector filter, such as sector\_name, to narrow the results to a single sector.

```python
import json
from urllib import request

APP_IDENTIFIER = "{your app identifier}"
THEME = "coordination-context/operational-presence"
LOCATION = "AFG"
LIMIT = 1000

def fetch_all(base_url, limit):
    results = []
    idx = 0
    while True:
        offset = idx * limit
        url = f"{base_url}&offset={offset}&limit={limit}"
        with request.urlopen(url) as response:
            page = json.loads(response.read())["data"]
        results.extend(page)
        if len(page) < limit:
            break
        idx += 1
    return results

base_url = (
    f"https://hapi.humdata.org/api/v2/{THEME}"
    f"?location_code={LOCATION}"
    f"&output_format=json"
    f"&app_identifier={APP_IDENTIFIER}"
)

data = fetch_all(base_url, LIMIT)
print(f"Retrieved {len(data)} records")
```

### 2. Combine two sources for a food security snapshot

Since HAPI standardizes indicators across sources, you can pull food prices and food security phases for the same country and analyze them together, without learning two separate APIs. Query each sub-category with the same location\_code, then join the results in your own code.

```python
import json
from urllib import request

APP_IDENTIFIER = "{your app identifier}"
LOCATION = "AFG"
LIMIT = 1000

def fetch_all(base_url, limit):
    results = []
    idx = 0
    while True:
        offset = idx * limit
        url = f"{base_url}&offset={offset}&limit={limit}"
        with request.urlopen(url) as response:
            page = json.loads(response.read())["data"]
        results.extend(page)
        if len(page) < limit:
            break
        idx += 1
    return results

def get(theme):
    base_url = (
        f"https://hapi.humdata.org/api/v2/{theme}"
        f"?location_code={LOCATION}"
        f"&output_format=json"
        f"&app_identifier={APP_IDENTIFIER}"
    )
    return fetch_all(base_url, LIMIT)

food_prices = get("food-security-nutrition-poverty/food-prices-market-monitor")
food_security = get("food-security-nutrition-poverty/food-security")
```

### 3. Population by admin level, with pagination

This loop shows the paging pattern in full: it pulls the baseline population for a country and keeps requesting pages until a page comes back shorter than the limit, meaning it has everything. Use `admin_level` and the admin filters shown in the API reference to focus on a specific administrative level.

```python
import json
from urllib import request
 
APP_IDENTIFIER = "{your app identifier}"
THEME = "geography-infrastructure/baseline-population"
LOCATION = "AFG"
LIMIT = 1000
 
def fetch_all(base_url, limit):
	results = []
	idx = 0
	while True:
    	offset = idx * limit
    	url = f"{base_url}&offset={offset}&limit={limit}"
    	with request.urlopen(url) as response:
            page = json.loads(response.read())["data"]
        results.extend(page)
    	if len(page) < limit:
            break
    	idx += 1
	return results
 
base_url = (
    f"https://hapi.humdata.org/api/v2/{THEME}"
    f"?location_code={LOCATION}"
    f"&output_format=json"
    f"&app_identifier={APP_IDENTIFIER}"
)
 
records = fetch_all(base_url, LIMIT)
print(f"Retrieved {len(records)} records")
```

### 4. Conflict events over time

Conflict event data goes back to 1997, so it is useful for a simple time series. Query the conflict events sub-category for a location and group the results by date in your own code. Once you have the data array, group by the date field to build a monthly or yearly trend.

```python
import json
from collections import Counter
from urllib import request

APP_IDENTIFIER = "{your app identifier}"
THEME = "coordination-context/conflict-events"
LOCATION = "AFG"
LIMIT = 1000

def fetch_all(base_url, limit):
    results = []
    idx = 0
    while True:
        offset = idx * limit
        url = f"{base_url}&offset={offset}&limit={limit}"
        with request.urlopen(url) as response:
            page = json.loads(response.read())["data"]
        results.extend(page)
        if len(page) < limit:
            break
        idx += 1
    return results

base_url = (
    f"https://hapi.humdata.org/api/v2/{THEME}"
    f"?location_code={LOCATION}"
    f"&output_format=json"
    f"&app_identifier={APP_IDENTIFIER}"
)

events = fetch_all(base_url, LIMIT)

# Group by year to build a yearly trend.
by_year = Counter(e["reference_period_start"][:4] for e in events)
for year in sorted(by_year):
    print(year, by_year[year])
```

### See it in action

For live examples built on HAPI, explore the [data availability dashboard](https://ocha-dap.github.io/viz-hapi-availability/), and the example dashboard linked on Tools and integrations.

Do you have an example you’d like to share? Reach out to us!

## Tools and integrations

You do not need to write code to use HAPI. These integrations and resources help you pull data into common tools.

* [API sandbox](https://hapi.humdata.org/docs): build and test a query and see the response.
* [Dashboard](https://ocha-dap.github.io/hdx-hapi-example/): an example dashboard with key figures, charts, and a map for all countries in HAPI.


---

# 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, and the optional `goal` query parameter:

```
GET https://docs.humdata.org/build/hdx-apis/hapi/examples-and-use-cases.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
