Building API Endpoints in Astro

Learn how we can build static and dynamic API endpoints in Astro.

Astro has powerful API capabilities. Thanks to its file-based routing, it’s possible to add API endpoints in the same straightforward manner as regular routes. API routes help us consume data in our front-end application in an easy-to-understand manner by providing URLs that return certain types of data in JSON format. Given below are the three most commonly used HTTP methods:

  • GET: It is used for retrieving data from an API.

  • POST: It is used for securely communicating with the server. It is often used for creating or updating resources.

  • DELETE: It is used for deleting resources.

In this lesson, we’ll explore how we can create both static and dynamic API endpoints using file-based routing.

Static endpoint

Static endpoints are the most basic form of API routes we can create. While they lack dynamic behavior, they can return any type of data. To create a new static API endpoint in Astro, we need to create a new file in the pages folder named <endpoint>.json.ts, where <endpoint> can be any arbitrary name.

In the following code widget, we already have an API-specific file created called api.json.ts. Inspect the contents of the file. Run the example and click “Send” in the first GET request in the API widget to see the response from the /api.json endpoint.

Get hands-on with 1400+ tech skills courses.