REST API
Backend
Frontend
Section titled “ggtFetch, a wrapper for fetch”
some-component.ts
some-component.ts
some-component.ts
/api/routes/brush/my-route/GET.ts
/api/routes/brush/my-route/GET-[id].ts
/api/routes/brush/my-route/POST.ts
Using AJAX to make REST calls to the backend.
ggtFetch, a wrapper for fetch
Section titled “ggtFetch, a wrapper for fetch”To make an AJAX call to the the Gadget backend, just use ggtFetch instead of fetch.
“ggt” in ggtFetch stand for “Gadget”.
It uses the same API but adds a few things:
- ensures the request goes thru the App Proxy (
/app/brush). - ensures the request is sent as
application/json. - adds useful HTTP headers for the backend to get information about current country, locale, …
- handle JSON and PDF content types, or falls back to text.
Example sending a simple GET request
Section titled “Example sending a simple GET request”const response = await ggtFetch("my-route")Example sending a GET request with one param
Section titled “Example sending a GET request with one param”const response = await ggtFetch("my-route/12345")Example sending a POST request
Section titled “Example sending a POST request”const response = await ggtFetch("my-route", { method: "POST", body: JSON.stringify({ name: "John Doe" }),});Building backend routes
Section titled “Building backend routes”⚠️ Please read and be familiar with Gadget HTTP routes
Create the matching route file in your Gadget app in /api/routes/brush.
Example handling a simple GET request
Section titled “Example handling a simple GET request”import { BrushContext } from "../../../../_brush/types";import { RouteHandler } from "gadget-server";
const handler: RouteHandler = async (context: BrushContext) => { return context.reply.send({name: "John Doe"});};
export default handler;Example handling a GET request with one param
Section titled “Example handling a GET request with one param”import { BrushContext } from "../../../../_brush/types";import { RouteHandler } from "gadget-server";
type RouteParams = { Params: { id: string } };
const handler: RouteHandler<RouteParams> = async (context: BrushContext<RouteParams>) => { return context.reply.send({ requestedId: context.request.params.id });};
export default handler;Example handling a POST request
Section titled “Example handling a POST request”import { BrushContext } from "../../../../_brush/types";import { RouteHandler } from "gadget-server";
type Body = { Body: { name: string } };
const handler: RouteHandler<Body> = async (context: BrushContext<Body>) => { return context.reply.send({ postedName: context.request.body.name });};
export default handler;