-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
New recipe: Call endpoints from the server (#3202)
* 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
1 parent
be208c4
commit dd6c16b
Showing
2 changed files
with
43 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | ||
``` |