Last active
July 12, 2019 11:49
-
-
Save magician11/bb701fe4284880436605a1a6995d0643 to your computer and use it in GitHub Desktop.
How to call Freshbooks Classic directly in Node.js using axios
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const axios = require("axios"); | |
const config = require("../security/auth.js"); | |
const callFreshbooks = async ( | |
xml, | |
apiUrl = config.freshbooks.url, | |
authToken = config.freshbooks.token | |
) => { | |
try { | |
const response = await axios({ | |
url: apiUrl, | |
data: xml, | |
auth: { | |
username: authToken, | |
password: "X" | |
}, | |
method: "POST" | |
}); | |
return response.data; | |
} catch (error) { | |
throw error; | |
} | |
}; | |
/* | |
e.g. get the project budget | |
docs: https://www.freshbooks.com/classic-api/docs/projects#project.get | |
*/ | |
const getProjectBudget = async projectId => { | |
try { | |
const data = await callFreshbooks(` | |
<?xml version="1.0" encoding="utf-8"?> | |
<request method="project.get"> | |
<project_id>${projectId}</project_id> | |
</request>`); | |
return parseFloat(data.match(/<hours>([\d|\.]+)/)[1]); | |
} catch (error) { | |
throw error; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I was using the freshbooks npm module, but started having issues with its dependencies as it was last updated 3 years ago.
It turns out even though the payloads are in XML, it's not too bad calling their classic API directly once you know how. Of course, then you need to process an XML response. But instead of having to use an XML library, since I know what specific fragment of data I want, I can use regular expressions to extract it.