Skip to main content

Python wrapper for DHIS2

Project description

Build BuildWin Coverage Latest version

A Python wrapper for DHIS2.

  • Common HTTP operations (GET, POST, PUT, PATCH, DELETE)
  • API paging for GETs
  • SQL Views
  • Server-side UID generation
  • CSV/JSON file loading
  • Defaults to JSON, supported GETs: XML, CSV, PDF, XLS
  • requests as HTTP library
  • logzero as drop-in logging library
  • Supported and tested on Python 2.7, 3.4-3.6 and DHIS2 versions >= 2.25


Simply use pipenv (or pip):

pipenv install --user --upgrade

For instructions on installing Python / pip see The Hitchhiker’s Guide to Python.


Create an API object:

from dhis2 import Dhis

api = Dhis('', 'admin', 'district', api_version=29, user_agent='myApp/0.1')

optional arguments:

  • api_version: DHIS2 API version
  • user_agent: submit your own User-Agent header

Then run requests on it:

r = api.get('organisationUnits/Rp268JB6Ne4', params={'fields': 'id,name'})

# { "name": "Adonkia CHP", "id": "Rp268JB6Ne4" }

Get info about the DHIS2 instance

# '2.29'

# 29

# '17f7f0b'

# ''

Load authentication from file

Load from a auth JSON file in order to not store credentials in scripts. Must have the following structure:

  "dhis": {
    "baseurl": "",
    "username": "admin",
    "password": "district"
from dhis2 import Dhis

api = Dhis.from_auth_file('path/to/auth.json', api_version=29, user_agent='myApp/1.0')

If no argument is specified, it tries to find a file called dish.json in:

  1. the DHIS_HOME environment variable
  2. your Home folder

API paging

Paging for larger GET requests.

Two possible ways:

  1. Process every page as they come in:
for page in api.get_paged('organisationUnits', page_size=100):
    # { "organisationUnits": [ {...}, {...} ] } (100 organisationUnits)
  1. Load all pages before proceeding (this may take a long time) - to do this, do not use for and add merge=True:
all_pages = api.get_paged('organisationUnits', page_size=100, merge=True):
# { "organisationUnits": [ {...}, {...} ] } (all organisationUnits)

Note: Returns directly a JSON object, not a requests.response object unlike normal GETs.

SQL Views

Get SQL View data as if you’d open a CSV file, optimized for larger payloads:

# poll a sqlView of type VIEW or MATERIALIZED_VIEW:
for row in api.get_sqlview('YOaOY605rzh', execute=True, criteria={'name': '0-11m'}):
    # {'code': 'COC_358963', 'name': '0-11m'}

# similarly, poll a sqlView of type QUERY:
for row in api.get_sqlview('qMYMT0iUGkG', var={'valueType': 'INTEGER'}):

# if you want a list directly, cast it to a ``list`` or add ``merge=True``:
data = list(api.get_sqlview('qMYMT0iUGkG', var={'valueType': 'INTEGER'}))
# OR
# data = api.get_sqlview('qMYMT0iUGkG', var={'valueType': 'INTEGER'}, merge=True)

Note: Returns directly a JSON object, not a requests.response object unlike normal GETs.

Beginning of 2.26 you can also use normal filtering on sqlViews. In that case, it’s recommended to use the stream=True parameter of the Dhis.get() method.

Generate UIDs

Get server-generated UIDs (not limited to 10000):

from dhis2 import generate_uids

uids = generate_uids(20000)
# ['Rp268JB6Ne4', 'fa7uwpCKIwa', ... ]

GET other content types

Usually defaults to JSON but you can get other file types:

r = api.get('organisationUnits/Rp268JB6Ne4', file_type='xml')
# <?xml version='1.0' encoding='UTF-8'?><organisationUnit ...

r = api.get('organisationUnits/Rp268JB6Ne4', file_type='pdf')
with open('/path/to/file.pdf', 'wb') as f:

Load a JSON file

from dhis2 import load_json

json_data = load_json('/path/to/file.json')
# { "id": ... }

Load a CSV file

from dhis2 import load_csv

for row in load_csv('/path/to/file.csv'):
    # { "id": ... }

# or for a normal list
data = list(load_csv('/path/to/file.csv'))


  • Color output depending on log level
  • DHIS2 log format including the line of the caller
  • optional logfile= specifies a rotating log file path (20 x 10MB files)
from dhis2 import setup_logger, logger

setup_logger(logfile='/var/log/app.log')'my log message')
logger.warn('missing something')
logger.error('something went wrong')
logger.exception('with stacktrace')
* INFO  2018-06-01 18:19:40,001  my log message [script:86]
* ERROR  2018-06-01 18:19:40,007  something went wrong [script:87]


There are two exceptions:

  • APIException: DHIS2 didn’t like what you requested. See the exception’s code, url and description.
  • ClientException: Something didn’t work with the client not involving DHIS2.

They both inherit from Dhis2PyException.


Feedback welcome!

  • Add issue
  • Install the dev environment (see below)
  • Fork, add changes to master branch, ensure tests pass with full coverage and add a Pull Request
pip install pipenv
git clone && cd
pipenv install --dev
pipenv run tests

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for, version 1.5.0
Filename, size File type Python version Upload date Hashes
Filename, size (14.5 kB) File type Wheel Python version py2.py3 Upload date Hashes View
Filename, size (10.5 kB) File type Source Python version None Upload date Hashes View

Supported by

Pingdom Pingdom Monitoring Google Google Object Storage and Download Analytics Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page