Routing
As you probably noticed from visiting the API page in the admin UI (http://localhost:4321/admin/api-specs), there are many automatically generated endpoints that support CRUD (Create - Read - Update - Delete) operations on you database tables.
In order to create custom routes with custom business rules, we use SonicJs's routing system, which is built on top of Astro's routing system. See the full docs here: Astro Routing.
If you are already familiar with Node/Express, you'll be right at home as the concepts and syntax are similar. Let's checkout a few simple examples:
src/pages/api/v1/example.ts
import {
return200WithObject,
return201,
return204,
return500,
} from "@services/return-types";
import type { APIRoute } from "astro";
export async function GET(context) {
return return200WithObject({ hello: "cruel world" });
}
export const POST: APIRoute = async ({ request }) => {
let body;
try {
body = await request.json();
} catch (error) {
return return500("Invalid JSON body");
}
return return201("Valid JSON body");
};
export const DELETE: APIRoute = ({ request }) => {
return return204();
};
export const ALL: APIRoute = ({ request }) => {
return return200WithObject({ message: "wildcard" });
};
Parameters
You will use the folder structure to specify the parameters that you want your APIs to use.
Below we have specified that the id
parameter is required by adding it in the file path of the ts file.
And this is how we extract that parameter in our route:
src/pages/api/v1/example/[id].ts
(note the [id]
in the file path)
import { return200WithObject } from "@services/return-types";
export async function GET({params}) {
return return200WithObject({ id: params.id});
}
An example url for this API would be: http://localhost:4321/api/v1/example/2077
.
Which would return the following JSON:
{
"id": "2077"
}
Easy Peasy right! To continue, make sure you've ⭐⭐⭐⭐⭐ starred the repo on Github 🙏. Here at SonicJs we work for stars my friend 🤩.
Need More?
SonicJs uses Astro for routing. Astro is a modern static site generator that is optimized for performance and minimal JavaScript. Astro is designed to deliver fast, secure, and scalable websites, offering features like partial hydration, automatic image optimization, and seamless integration with popular frameworks such as React, Vue, and Svelte.