DHIS2 Web API and Python

Hi All,

Just in case you were wondering how to get DHIS2 data from python, see below.


Created on 17/12/2018

@author Charles Waka
"""
#Python code for getting data from DHIS2
import getpass
import numpy as np
import pandas as pd
import requests as rq
from io import StringIO

#DHIS2 username and password variables
dhis_uname="admin"
dhis_pwd="district"
dhis_url="https://play.dhis2.org/dev/api/reportTables/KJFbpIymTAo/data.csv"

#If you need to protect your password, you can use getpass
#response=rq.get(dhis_url, auth=(dhis_uname,getpass.getpass()))
response=rq.get(dhis_url, auth=(dhis_uname,dhis_pwd))

#Read the data to a pandas dataset
dset=pd.DataFrame(pd.read_csv(StringIO(response.text)))

#Get column names of data set
print(dset.columns.values) 

#Print a few rows of the dataset
dset.head(10)

#You can view the data types of your set
dset.dtypes

Regards,
Charles Waka.

9 Likes

Thanks for sharing this @Waka_Wafubwa.

Best,
James.

1 Like

Hi @charles.waka, thank you for sharing this. It’s nice however, not a good practice to follow. I would discourage storing usernames and passwords openly for security reasons.

1 Like

I just started building an application on Django and good to have a group to talk to.

2 Likes

I also use Python for scripting DHIS2 API. It will be nice to have a group or a thread with collection of common use-cases/snippets.

For instance, to update an option set dynamically, I used this:

import requests
import logging

logging.basicConfig(level=logging.DEBUG)
API_URL = 'http://username:password@localhost:8000/api'


def set_optionset(optionset_id, options):
    url = API_URL + '/optionSets/{}/options'.format(optionset_id)
    res = requests.patch(url, json={'options': options})
    res.raise_for_status()
    return res.json()

Example:

options = [
    {'code': 'apple', 'name': 'Apple'},
    {'code': 'ball', 'name': 'Ball'},
]


# this will replace existing options in optionset with the one provided
response = set_optionset('PdiTQOAOAqN', options)
2 Likes

Hello,

I have an update on the pypi api. I kept having error on post with the guide on the official site.

r = api.post(‘metadata’, json={‘dataElements’: [ … ] })
print(r.status_code) # 200

this is not work for me.

I eventually tried the using:

api.post(‘metadata’, data={‘dataElements’: [ … ] })

GET and POST Requests Using Python - GeeksforGeeks

Kept having the error that json is not a recognized arg but data is.

@Amina_Abba_Gana1 @Amina_Abba_Gana @aabbagana

@dhuser , Thanks so much for your contribution on the pypi wrapper. You rock.

2 Likes

Hi,

both json= and data= should be supported as arguments.
If you’re not using the latest version you should upgrade the package - you can check with:
pip show dhis2.py
and upgrade with
pip install dhis2.py --upgrade

Please note that it is not an official DHIS 2 Python package but hopefully still useful.

1 Like