36 lines
1.4 KiB
Markdown
36 lines
1.4 KiB
Markdown
---
|
|
title: >
|
|
Creating API endpoints with Astro
|
|
pubDate: 2023-02-09
|
|
permalink: >-
|
|
archive/2023/02/09/creating-api-endpoints-with-astro
|
|
tags:
|
|
- astro
|
|
---
|
|
|
|
As well as [fetching API data]({{site.url}}/archive/2023/02/08/fetching-api-data-with-astro), 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:
|
|
|
|
```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[]),
|
|
};
|
|
};
|
|
```
|
|
|
|
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.
|