DHIS2 has a powerful Web API which can be used to integrate applications together. In this section, we will illustrate a few trivial examples of the use of the Web API, and how we can retrieve data and metadata for use in R. The Web API uses basic HTTP authentication (as described in the Web API section of this document). Using two R packages “RCurl” and “XML”, we will be able to work with the output of the API in R. In the first example, we will get some metadata from the database.
#We are going to need these two libraries require(RCurl) require(XML) #This is a URL endpoint for a report table which we can #get from the WebAPI. url<-"https://apps.dhis2.org/dev/api/reportTables/KJFbpIymTAo/data.csv" #Lets get the response and we do not need the headers #This site has some issues with its SSL certificate #so lets not verify it. response<-getURL(url,userpwd="admin:district" ,httpauth = 1L, header=FALSE,ssl.verifypeer = FALSE) #Unquote the data data<-noquote(response) #here is the data. mydata<-read.table(textConnection(data),sep=",",header=T) head(mydata)
Here, we have shown how to get some aggregate data from the DHIS2 demo database using the DHIS2’s Web API.
In the next code example, we will retrieve some metadata, namely a list of data elements and their unique identifiers.
#Get the list of data elements. Turn off paging and links #This site has some issues with its SSL certificate #so lets not verify it. url<-"https://apps.dhis2.org/dev/api/dataElements.xml? paging=false&links=false" response<-getURL(url,userpwd="admin:district", httpauth = 1L, header=FALSE,ssl.verifypeer = FALSE) #We ned to parse the result bri<-xmlParse(response) #And get the root r<-xmlRoot(bri) #Parse out what we need explicitly, in this case from the first node #Just get the names and ids as separate arrays de_names<-xmlSApply(r[['dataElements']],xmlGetAttr,"name") de_id<-xmlSApply(r[['dataElements']],xmlGetAttr,"id") #Lets bind them together #but we need to be careful for missing attribute values foo<-cbind(de_names,de_id) #Recast this as a data frame data_elements<-as.data.frame(foo, stringsAsFactors=FALSE,row.names=1:nrow(foo)) head(data_elements)
Note that the values which we are interested in are stored as XML attributes and were parsed into two separate matrices and then combined together into a single data frame.