Blog / Code Editor
Code editor can be a powerful feature for logic that can’t be achieved with the UI. With this article, we’ll learn how we can call an external REST API endpoint in the Code editor.
Code editor can be a powerful feature for logic that can’t be achieved with the UI. With this article, we’ll learn how we can call an external REST API endpoint in the Code editor.
You can find code editor inside Canonic at different places:
2. Inside API Endpoints
Similar to the above, in the API tab itself, you can find DB Triggers, Scheduled triggers, and Integration Triggers in the left-hand panel (step 2 in the above image) - all of them have code editor as well in the properties panel similar to API Endpoints.
Inside Code editor, you can use fetch library to make the API request.
Inside every code editor, existing code will look something like this:
module.exports = async function .... {
}
To make the fetch call, you have to request node-fetch
inside the function, and then execute your API request.
Example code:
module.exports = async function ... {
...
const fetch = require('node-fetch')
const response = await fetch('<https://example.com/api/endpoint>')
const responseJson = await response.json();
// ResponseJson becomes an object that you can use now in the function
// as required
...
}
API Request to multiple external endpoints
Example code:
module.exports = async function ... {
...
const fetch = require('node-fetch')
const [responseOne, responseTwo, responseThree] = await Promise.all([
fetch('<https://example.com/api/endpoint1>'),
fetch('<https://example.com/api/endpoint2>'),
fetch('<https://example.com/api/endpoint3>'),
]);
const [responseJsonOne, responseJsonTwo, responseJsonThree] = await Promise.all([
responseOne.json(),
responseTwo.json()
responseThree.json()
]);
// ResponseJsonOne, ResponseJsonTwo, ResponseJsonThree - become an object that
// you can now use futher in the function
// as required
...
}
You can further refer to node-fetch documentation to know more about the different methods of the library.
Aside from the autogenerated CRUD Endpoints for your tables. You can also create your own custom endpoint.
The steps to create endpoints on Canonic are easy.
Let us know if you have any questions or doubts. Happy to help!
Start using canonic's fullstack solution to build internal tools for free