Creating API endpoints with Astro

As well as fetching API data, you can also use Astro to generate your own API endpoints.

This is an example of an endpoint that I recently created as part of a demo application:

// 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[]),
  };
};

The train data is imported from a JSON file, and Astro's APIRoute is responsible for setting the appropriate response headers.

For server-side rendered applications, you can also have endpoints for post, del and all, though for this example, I only needed to support GET requests.

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.

And, as the example application that consumes the data is also written with Astro, having them both using the same solution has advantages too.

- Oliver

Was this interesting?

Sign up here and get more like this delivered straight to your inbox every day.

About me

Picture of Oliver

I'm an Acquia-certified Drupal Triple Expert with 17 years of experience, an open-source software maintainer and Drupal core contributor, public speaker, live streamer, and host of the Beyond Blocks podcast.