Endpoints and RESTful API

Qwik City is able to create a RESTful API for your application using Endpoints. Endpoint routes are created the same as how you would create a "page", except the filename should end with .ts instead of .tsx. An index.ts in the src/routes directory is only for data, such as a json response, while an index.tsx is for an HTML page. There is no need to put the "endpoint" routes into a specific api directory within src/routes.

Both "page" and "endpoints" are the same except for one difference: a page exports a default component$() to render HTML, whereas an endpoint exports only HTTP request and response handlers. To learn about defining a page component, you can read more here. An endpoint route however, is used only for the purpose of responding with data.

Example API endpoint route

// File: src/routes/product/[skuId]/index.ts
import type { RequestHandler } from '@builder.io/qwik-city';

interface ProductData {
  skuId: string;
  price: number;
  description: string;
}

export const onGet: RequestHandler<ProductData> = async ({ params }) => {
  // put your DB access here, we are hard coding a response for simplicity.
  return {
    skuId: params.skuId,
    price: 123.45,
    description: `Description for ${params.skuId}`,
  };
};

export const onPost: RequestHandler<ProductData> = async ({ params }) => { ... }
export const onPut: RequestHandler<ProductData> = async ({ params }) => { ... }
export const onPatch: RequestHandler<ProductData> = async ({ params }) => { ... }
export const onDelete: RequestHandler<ProductData> = async ({ params }) => { ... }
Made with ❤️ by