API's authentication in Node.js


(CommCare N00b) #1

I’m trying to use Node.js to connect to the API’s to get the form structure.

I’m a bit unclear as to the example provided using API keys:

curl -H "Authorization: ApiKey [USERNAME]:[API_KEY]" '[URL]'

This is how I format my headers to initiate the request:

	var options = {
	    host: url,
	    port: 80,
	    method: 'POST',
	    rejectUnauthorized: false,
	    requestCert: true,
	    agent: false,
		headers: {
			'Authorization': 'ApiKey',
			'john.doe@domain.org':apikey
		}	    
	};

But that does not work, this is the error i’m getting:
https://www.commcarehq.org/a/domain-test/api/v0.5/application/6f3c4e0aa9157fe0a3cfb2a94c5b8540
TypeError [ERR_INVALID_HTTP_TOKEN]: Header name must be a valid HTTP token [“john.doe@domain.org”]
at validateHeader (_http_outgoing.js:499:11)

Please advise.


(Simon Kelly) #2

In the example there is only a single header with

name = Authorization
value = ApiKey [USERNAME]:[API_KEY]

So your code should look more like this:

var options = {
	    host: url,
	    port: 80,
	    method: 'POST',
	    rejectUnauthorized: false,
	    requestCert: true,
	    agent: false,
		headers: {
			'Authorization': 'ApiKey john.doe@domain.org:apikey'
		}	    
	};

(CommCare N00b) #3

Ok, that’s a step in the right direction, however the URL i’m providing is wrong (tested using curl):

curl -H “Authorization: ApiKey email@domain.org:apikey” ‘https://www.commcarehq.org/a/DomainFromURL/api/v0.5/application/AppID

I test this and it says page does not exist.

By AppID, where do you get this information? I think that may be the culprit?


(Simon Kelly) #4

I think you just need to end the URL with a ‘/’ otherwise you’ll get a 302 Redirect response.


(CommCare N00b) #5

One last question: is there an API that allows me to see the form structure? What i mean ny that is:

  • question 1: type: text, requluired: true, label: what is your name, etc…

(Simon Kelly) #6

Yes, there is the Application Structure API


(CommCare N00b) #7

Ok, for all of you having issues, here’s the code in python that works to connect:

import requests
url = ‘https://www.commcarehq.org/a/domain/api/v0.5/application/appid/
headers = {‘Authorization’:‘ApiKey username@domain.org:ApiKey’}
r = requests.get(url, headers=headers)

return (r.json())


(Chriss pratt) #8

Hi, May be not the best idea to use production. Just google for it – here is something that I could find where you can learn how to use a JSON Source Connector, XML Source Connector, and REST API Task.
Check it out, https://zappysys.com/blog/howto-import-json-rest-api-power-bi/