This section walks you through importing data values into DHIS2 using the dhis2-python-client
library.
Below are crucial steps to follow:
- Get credentials
- Connect to DHIS2 and verify access
- Build a valid
dataValueSets
payload (JSON or CSV) - Send your payload
1) Configure your environment and connect to DHIS2¶
import pandas as pd
from dhis2_client import DHIS2Client
from dhis2_client.settings import ClientSettings
# Client configuration
cfg = ClientSettings(
base_url="http://localhost:8080",
username="admin",
password="district")
client = DHIS2Client(settings=cfg)
info = client.get_system_info()
# Check if everything is working.
# You should see your current DHIS2 version info.
print("▶ Current DHIS2 version:", info["version"])
▶ Current DHIS2 version: 2.42.2-SNAPSHOT
2) Construct payload¶
Data values can be sent to DHIS2 one-by-one or in batch. The one-by-one approach is very handy especially when users are entering data manually. For batch import DHIS2 provides dataValueSets
endpoint. Below is a sample payload demonstrating batch data import.
data = {
"dataValues": [
{
"orgUnit": "O6uvpzGd5pu",
"period": "20250101",
"value": "23.68",
"dataElement": "VJwwPOOvge6"
},
{
"orgUnit": "fdc6uOvgoji",
"period": "20250101",
"value": "23.96",
"dataElement": "VJwwPOOvge6"
},
{
"orgUnit": "lc3eMKXaEfw",
"period": "20250101",
"value": "24.52",
"dataElement": "VJwwPOOvge6"
},
{
"orgUnit": "jUb8gELQApl",
"period": "20250101",
"value": "23.06",
"dataElement": "VJwwPOOvge6"
},
{
"orgUnit": "PMa2VCrupOd",
"period": "20250101",
"value": "24.45",
"dataElement": "VJwwPOOvge6"
},
{
"orgUnit": "kJq2mPyFEHo",
"period": "20250101",
"value": "23.27",
"dataElement": "VJwwPOOvge6"
}
]
}
3) Send your payload¶
Once we are done preparing our payload we can proceed to send it to DHIS2. dhis2-python-client
provides both direct access to raw DHIS2 API like client.post(/api/dataValueSets, ...)
and convenient method like client.post_data_value_set(...)
. Since we saw convenient methods in the above metadata creation steps, let’s use raw DHIS2 API access this time.
res = client.post("/api/dataValueSets", json=data)
4) Troubleshooting¶
- Unauthorized: Check credentials and user permissions.
- Not found: Verify data element, org unit, and combos (if you have used non-default ones) exist.
- Conflicts: Ensure dataset assignments and period are correct.
- Locked periods: Unlock dataset period if needed.
- Value types: Match the data element value type.