Skip to content

Commit

Permalink
New recipe: Call endpoints from the server (#3202)
Browse files Browse the repository at this point in the history
* New recipe: Call endpoints from the server

* Apply suggestions from code review

Co-authored-by: Sarah Rainsberger <[email protected]>

* Update recipe

* Update link

* Add related recipe link

* Move recipe links

---------

Co-authored-by: Sarah Rainsberger <[email protected]>
Co-authored-by: Elian ☕️ <[email protected]>
  • Loading branch information
3 people authored Jul 26, 2023
1 parent be208c4 commit dd6c16b
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/content/docs/en/core-concepts/endpoints.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,8 @@ Everything described in the static file endpoints section can also be used in SS
But, unlike in `static` mode, when you configure `server` mode, the endpoints will be built when they are requested. This unlocks new features that are unavailable at build time, and allows you to build API routes that listen for requests and securely execute code on the server at runtime.
<RecipeLinks slugs={["en/recipes/call-endpoints" ]}/>
:::note
Be sure to [enable SSR](/en/guides/server-side-rendering/#enabling-ssr-in-your-project) before trying these examples.
:::
Expand Down Expand Up @@ -224,4 +226,3 @@ export async function get({ params, redirect }) {
return redirect(link, 307);
}
```
41 changes: 41 additions & 0 deletions src/content/docs/en/recipes/call-endpoints.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
---
title: Call endpoints from the server
description: Learn how to call endpoints from the server in Astro.
i18nReady: true
type: recipe
---

Endpoints can be used to serve many kinds of data. This recipe calls a server endpoint from a page's component script to display a greeting, without requiring an additional fetch request.

## Prerequisites

- A project with [SSR](/en/guides/server-side-rendering/) (output: 'server') enabled

## Recipe

1. Create an endpoint in a new file `src/pages/api/hello.ts` that returns some data:

```ts title="src/pages/api/hello.ts"
import type { APIRoute } from 'astro'

export const get: APIRoute = () => {
return new Response(
JSON.stringify({
greeting: 'Hello',
}),
)
}
```

2. On any Astro page, import the `get()` method from the endpoint. Call it with the [`Astro` global](/en/reference/api-reference/#astro-global) to provide the request context, and use the response on the page:

```astro title="src/pages/index.astro"
---
import { get } from './api/hello.ts'
let response = await get(Astro)
const data = await response.json()
---
<h1>{data.greeting} world!</h1>
```

0 comments on commit dd6c16b

Please sign in to comment.