Astro JS - Endpoints



What are Endpoints?

Endpoints are server-side routes that are used handle requests and responses from the client. Any .ts or .js file in the src/pages directory is considered an endpoint. Endpoints can be used to fetch data from a database, perform calculations, setup authentication, or generate dynamic content.

Astro frameworks have inbuilt features to setup endpoints inside the application. In static-sites, the endpoints are called at build time to generate the static files. But in server-side rendered applications, custom endpoints turn into live server endpoints that are called on request. Let's see how to create endpoints in Astro.

How to create Endpoints in Astro?

Follow the below steps to create an endpoint in Astro.

Step 1: Create a API File

First, open your Astro project and navigate to the src/pages directory. Create a new file with the .ts or .js extension. For example, create a file named hello.ts.

Step 2: Define Endpoint Function

In the file created in the previous step, define a simple javascript function that returns a JSON object. For example, the following code defines an endpoint function that returns a JSON object with a message property.

// File: src/pages/hello.ts

export async function GET() {
    return new Response(JSON.stringify(
        { message: "Hello from Astro API!" }), 
        {headers: { "Content-Type": "application/json" }
    });
}

Step 3: Access the Endpoint

Now, your endpoint is ready. You can access it by navigating to the URL http://localhost:4321/hello.

Astro Endpoints

Types of Astro Endpoints

There are two types of Astro endpoints:

Static File Endpoints

Static file endpoints are used to serve static files such as images, CSS, and JavaScript files. It export a GET function (optionally async) that receives a context object with properties similar to the Astro global. The context object contains information about the request, such as the URL, headers, and cookies. The GET function should return a Response object that contains the file content and headers.

To create a static endpoint, add a .js or .ts file to the /pages directory. The .js or .ts extension will be removed during the build process, so the name of the file should include the extension of the data you want to create. For example, src/pages/data.json.ts will build a /data.json endpoint.

Example 1 - Return Json File

In the example below, we created a /data.json endpoint that returns a JSON object with a message property.

// File: src/pages/built-with.json.ts
export async function GET({params, request}) {
  return new Response(
    JSON.stringify({
      name: 'Astro',
      url: 'https://astro.build/'
    })
  )
}

Output

Astro Endpoints JSON

Example 2 - Return Images

In the example below, we created image endpoint that returns a JPEG image.

// File: src/pages/image.jpg.ts

export async function GET({ params, request }) {
    const response = await fetch("https://docs.astro.build/assets/full-logo-light.png");
    return new Response(await response.arrayBuffer());
}

Output

Astro Endpoints Image

Server Endpoints

In the case of server endpoints, in addition to the GET function, you can export a function with the name of any HTTP method. When a request comes in, Astro will check the method and call the corresponding function. You can also export an ALL function to match any method that doesnt have a corresponding exported function. If there is a request with no matching method, it will redirect to your sites 404 page.

// File: src/pages/method.json.ts

export const GET: APIRoute = ({ params, request }) => {
    return new Response(JSON.stringify({
        message: "This was a GET!"
      })
    )
  }
  
  export const POST: APIRoute = ({ request }) => {
    return new Response(JSON.stringify({
        message: "This was a POST!"
      })
    )
  }
  
  export const DELETE: APIRoute = ({ request }) => {
    return new Response(JSON.stringify({
        message: "This was a DELETE!"
      })
    )
  }
  
  export const ALL: APIRoute = ({ request }) => {
    return new Response(JSON.stringify({
        message: `This was a ${request.method}!`
      })
    )
}

Dynamic API Routing

The endpoints also support dynamic routing features. You can name files in bracketed parameters and export a getStaticPaths() function. Then, you can access the parameter using the params property passed to the endpoint function:

// File: src/pages/api/[id].json.ts

import type { APIRoute } from 'astro';

const usernames = ["Sarah", "Chris", "Yan", "Elian"]

export const GET: APIRoute = ({ params, request }) => {
  const id = params.id;
  return new Response(
    JSON.stringify({
      name: usernames[id]
    })
  )
}

export function getStaticPaths() {
  return [
    { params: { id: "0"} },
    { params: { id: "1"} },
    { params: { id: "2"} },
    { params: { id: "3"} }
  ]
}

Output

Astro Endpoints Dynamic API
Advertisements