Central API examples

Hi,

I had to give some support to folk that wanted to use the ODK Central API to extract data.

I think it would be useful to have some examples for user not so experienced.

Examples for example on how to create a java method to download csv or zip etc...

Example csv

public static void main(String[] args) {
	Client client = ClientBuilder.newClient();
	Response response = client.target("https://*MYCENTRAL*/v1/projects/*projectId*/forms/*xmlFormId*/submissions.csv")
			.request(MediaType.TEXT_PLAIN_TYPE).
			header("Authorization", "Bearer *AUTHTOKEN*").
			get();

	File downloadedFile = new File("\\*PATHTOSAVE*\\submission.csv");
	String str = response.readEntity(String.class);
    BufferedWriter writer;
	try {
		writer = new BufferedWriter(new FileWriter(downloadedFile));
	    writer.write(str);
	    
	    writer.close();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

}

Example zip

public static void main(String[] args) {
	InputStream inputStream = null;
	OutputStream outputStream = null;
    int responseCode;
    String responseMessageFromServer = null;
    String filePath = null;
	// TODO Auto-generated method stub
	Client client = ClientBuilder.newClient();
	Response response = client.target("https://*MYCENTRAL*/v1/projects/*projectId*/forms/*xmlFormId*/submissions.csv.zip?media=true&%24filter=__system%2FsubmissionDate%20gt%202021-01-01%20and%20__system%2FsubmissionDate%20lt%202021-01-25")
			.request(MediaType.TEXT_PLAIN_TYPE).
			header("Authorization", "Bearer *AUTHTOKEN*").
			get();

	responseCode = response.getStatus();

    System.out.println("Response code: " + responseCode);

    if (response.getStatus() != 200) {
       throw new RuntimeException("Failed with HTTP error code : " + responseCode);
    }
	
    // get response message
    responseMessageFromServer = response.getStatusInfo().getReasonPhrase();
    System.out.println("ResponseMessageFromServer: " + responseMessageFromServer);
    // read response
	inputStream = response.readEntity(InputStream.class);
	try {
		filePath = "\\*PATHTOSAVE*\\submission.zip";
        outputStream = new FileOutputStream(filePath);
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
             outputStream.write(buffer, 0, bytesRead);
        }
        
        System.out.println("downloaded successfully at " + filePath);
      	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}

Maybe some links to OData Built-in Filter Operations or Built-in Query Functions directly on the page of export submissions and some practical examples on filters:

e.g. I want to filter submission between 2 dates "filter=__system%2FsubmissionDate%20gt%202021-01-01%20and%20__system%2FsubmissionDate%20lt%202021-01-31"

Do you think this kind of info could be directly on ODK Central API · Apiary or maybe on the forum?

5 Likes