<p>As well as <a href="/daily/2023/02/08/fetching-api-data-with-astro">fetching API data</a>, you can also use Astro to generate your own API endpoints.</p>
<p>This is an example of an endpoint that I recently created as part of a demo application:</p>
<pre><code class="javascript">// trains.json.ts
import data from "@/data.json";
import type { APIRoute } from "astro";
import type { Train } from "@/types";
export const get:APIRoute = () => {
return {
body:JSON.stringify(data.trains as Train[]),
};
};
</code></pre>
<p>The train data is imported from a JSON file, and Astro's <code>APIRoute</code> is responsible for setting the appropriate response headers.</p>
<p>For server-side rendered applications, you can also have endpoints for <code>post</code>, <code>del</code> and <code>all</code>, though for this example, I only needed to support GET requests.</p>
<p>This is something that I've used a db-json library for previously, but being able to do this in Astro seemed like a good fit as I can easily manage lists of stations as well as a single station from one JSON file but I can just take the static HTML that Astro generates and upload it to a static hosting solution which simplifies the hosting side of things a lot.</p>
<p>And, as the example application that consumes the data is also written with Astro, having them both using the same solution has advantages too.</p>
<p>As well as <a href="/daily/2023/02/08/fetching-api-data-with-astro">fetching API data</a>, you can also use Astro to generate your own API endpoints.</p>
<p>This is an example of an endpoint that I recently created as part of a demo application:</p>
<pre><code class="javascript">// trains.json.ts
import data from "@/data.json";
import type { APIRoute } from "astro";
import type { Train } from "@/types";
export const get:APIRoute = () => {
return {
body:JSON.stringify(data.trains as Train[]),
};
};
</code></pre>
<p>The train data is imported from a JSON file, and Astro's <code>APIRoute</code> is responsible for setting the appropriate response headers.</p>
<p>For server-side rendered applications, you can also have endpoints for <code>post</code>, <code>del</code> and <code>all</code>, though for this example, I only needed to support GET requests.</p>
<p>This is something that I've used a db-json library for previously, but being able to do this in Astro seemed like a good fit as I can easily manage lists of stations as well as a single station from one JSON file but I can just take the static HTML that Astro generates and upload it to a static hosting solution which simplifies the hosting side of things a lot.</p>
<p>And, as the example application that consumes the data is also written with Astro, having them both using the same solution has advantages too.</p>