Manually request an API inside your code with axios
When an API is not available inside Meta API, you can manually make request directly from your code.
You can do it with the axios
library, directly integrated inside your Spell.
The simple GET request
You can make a GET request very easily with
const myRequest = await axios.get(
"https://api.coindesk.com/v1/bpi/currentprice.json"
);
//To access data, use the data property inside your initialized variable
console.log(myRequest.data);
If you have to put some parameters, like headers, you can do it like this:
const myRequest = await axios.get(
"https://api.coindesk.com/v1/bpi/currentprice.json",
{
headers: {
"x-api-key": "abc123",
},
}
);
console.log(myRequest.data);
The complete POST request
When you want to make a full POST request with a body, you can use the fully configurable version of axios
:
const myRequest = await axios({
method: "POST",
url: "https://test.com",
headers: {
apikey: "test123",
},
data: {
firstname: "Harry",
lastname: "Potter",
},
});
The full documentation of axios
is available here: https://axios-http.com/docs/req_config
POST Request with a form
If you want to use a form with axios, you have to add the form-data
dependency and to name it FormData
(as a alias):
You don't have to add a require inside your code.
Then, you can use the form with axios
with the following code:
const form = new FormData();
form.append("Name", "Thomas Anderson");
form.append("ID", "abc1234");
const myRequest = await axios.post("https://myapi.test", form, {
headers: {
...form.getHeaders(), //This line will inject correct headers for using form
},
});
console.log(myRequest.data);
Troubleshooting
A known issue is that you can't to log directly the response of axios directly.
Therefore, console.log(myResult)
, console.info(myResult)
, console.error(myResult)
, etc. will not work and return a 500 error.