Calling non-Airplane APIs
While views make it easy to integrate Airplane tasks using
Task backed components or
React hooks, there may be times when you want to call a
non-Airplane backend API.
Wrap the API call in an Airplane task (recommended)
Wrap the API call in an Airplane task (recommended)
It's easy to create a small Airplane task that calls an API. By wrapping the API call in an Airplane
task, you can utilize Task backed components which provide
automatic data fetching, loading and error state.
Rest task
Rest task
The easiest way to call an API via Airplane task is by creating a REST task. Follow
REST getting started to deploy a REST task that calls your API.
JavaScript task
JavaScript task
Follow the Getting started guide to create a JavaScript task. Include any
Parameters that your API call needs.
The body of your task should look something like:
javascriptCopied1const endpoint = "https://catfact.ninja/fact";23export default async function (params) {4const response = await fetch(endpoint);5if (!response.ok) {6throw new Error(response.status);7}89const responseData = await response.json();10// The catfacts API returns a response of type { fact: string }.11return responseData.fact;12}
Call the API directly from your view
Call the API directly from your view
If you do not want to wrap your API call in an Airplane task, you can call the API directly from
your view using the built in
fetch
API or another data fetching library.Any secret API keys or other sensitive authentication pieces should not be included directly in a
view.
tsxCopied1const [catFact, setCatFact] = useState("");2useEffect(() => {3async function fetchCatFact() {4try {5const response = await fetch("https://catfact.ninja/fact");6if (!response.ok) {7alert(`Errored with status ${response.status}`);8}9const data = await response.json();10setCatFact(data.fact);11} catch (error) {12return alert(error);13}14}15fetchCatFact();16}, []);17if (!catFact) {18return <Loader />;19}20return (21<Stack>22<Title>Tell me a cat fact</Title>23<Text size="lg">{catFact}</Text>24</Stack>25);