Back to Blog Page
Frontend Development

Astro Data Fetching: How to Fetch Data in Astro

Astro Data Fetching: How to Fetch Data in Astro

Written by Kolade Chris | Nov 16, 2024 | #Astro | 2 minutes Read

Like I said on Twitter (now X) a while ago, Astro is the only framework that makes everything ridiculously uncomplicated for you.

In this article, I want to show you how ridiculously uncomplicated it is to fetch data in Astro using a simple API from JSON Placeholder.

How to Fetch Data in Astro

To get started, I have installed an empty Astro project. Here are the prompt choices I made during the installation:

Astro fresh installation

Here’s the initial folder structure of the project:

Astro installation folder structure

You only need the traditional fetch API to fetch the data. Open up a code fence inside src/pages/index.astro and paste this inside it:

1
---
2
fetch("https://jsonplaceholder.typicode.com/posts")
3
.then(res => res.json())
4
.then(data => console.log(data))
5
---

That’s all you need, but Astro has a beautiful way to enhance and simplify this. You might also want to pass the data into the template so you can see it in the browser. Keep reading so I can show you this.

To simplify the data fetching, Astro has a top level await built-in, so you don’t need an async function to use it. YOu can use this for the data fetching:

1
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
2
const data = await response.json();
3
4
console.log(data);

In the template, you can stringify the data for a start:

1
Data: {
2
JSON.stringify(data);
3
}

Then map through it:

1
<body>
2
<h1>Astro Data Fetching</h1>
3
{data.map((post:any) => (
4
<div>
5
<h2>{post.title}</h2>
6
<p>{post.body}</p>
7
</div>
8
))}
9
</body>

Astro installation folder structure

Thank you for reading!

If you want to fetch the data from a headless CMS, look through the Astro docs for data fetching from a CMS, and the CMS you want to use.