Skip to content

REST API

Backend Frontend

Using AJAX to make REST calls to the backend.

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.
some-component.ts
const response = await ggtFetch("my-route")

Example sending a GET request with one param

Section titled “Example sending a GET request with one param”
some-component.ts
const response = await ggtFetch("my-route/12345")
some-component.ts
const response = await ggtFetch("my-route", {
method: "POST",
body: JSON.stringify({ name: "John Doe" }),
});

⚠️ Please read and be familiar with Gadget HTTP routes

Create the matching route file in your Gadget app in /api/routes/brush.

/api/routes/brush/my-route/GET.ts
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”
/api/routes/brush/my-route/GET-[id].ts
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;
/api/routes/brush/my-route/POST.ts
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;