API routing
Build HTTP APIs with controllers, route decorators, parameter extraction, and structured responses in AntelopeJS.
Prerequisites
Use this guide to expose HTTP endpoints from a module. Start with a local project, then install @antelopejs/interface-api in the module that declares the routes.
For a map of the complete request path, see the task API flow. This guide starts with only its HTTP provider and controller. Authentication and storage are separate additions.
The package supplies the contract and decorators, not a listening server. Keep the local module from the quick start and add this provider entry to the project's modules map:
api: {
source: { type: "package", package: "@antelopejs/api", version: "1.3.4" },
config: {
servers: [{ protocol: "http", host: "127.0.0.1", port: 3000 }],
publicBaseUrl: "http://localhost:3000",
},
},
Enable experimentalDecorators and emitDecoratorMetadata in the module's TypeScript configuration. If you choose another provider version, check its interface range and configuration before you upgrade.
Verify a first endpoint
Create a controller with no database or authentication dependency:
import { Controller, Get } from "@antelopejs/interface-api";
class HealthController extends Controller("/api") {
@Get("health")
health() {
return { status: "ok" };
}
}
Import the file from src/index.ts with import "./controllers/health";. The decorators register the route when the file runs, so a controller file that nothing imports adds no route.
Start the project, then request /api/health on the configured API port:
curl -i http://127.0.0.1:3000/api/health
Expect a successful response with {"status":"ok"}. A connection error points to the server configuration. A 404 points to the controller import, the prefix, or the route path. Add request parameters and response handling only after this request works.
Creating controllers
A controller groups related routes under a shared base path. The Controller function returns a base class bound to a URL path, and you extend that class to define your controller. A method becomes a route handler when you decorate it with an HTTP method decorator.
import {
Controller,
Get,
Post,
Put,
Delete,
Parameter,
JSONBody,
} from "@antelopejs/interface-api";
class UserController extends Controller("/api/users") {
@Get("")
async listUsers() {
return { users: [] };
}
@Get(":id")
async getUser(@Parameter("id") id: string) {
return { id, name: "Alice" };
}
@Post("")
async createUser(@JSONBody() body: { name: string; email: string }) {
return { id: "new-id", ...body };
}
@Put(":id")
async updateUser(@Parameter("id") id: string, @JSONBody() body: any) {
return { id, ...body };
}
@Delete(":id")
async deleteUser(@Parameter("id") id: string) {
return { success: true };
}
}
The framework sends the value a handler returns as a JSON response. Controller is not a decorator. It returns a class that you extend with extends Controller("/path").
A path segment that starts with :, such as :id, declares a route parameter, and @Parameter("id") reads it. The default source of @Parameter is "param". Pass an empty string, as in @Get(""), to bind the route to the controller's base path. If you omit the argument, the method name becomes the last path segment. The decorator on each parameter decides whether the value comes from the URL path, the query string, or a header.
TypeScript annotations on @JSONBody() parameters do not validate untrusted JSON at runtime. Validate request fields before you use or store them. The example handlers above show routing and do not persist records.
HTTP responses
The HTTPResult class sets the status code and the response headers. Without HTTPResult, every successful response has status 200. Use HTTPResult when you need another status code or custom headers.
import {
Controller,
Post,
JSONBody,
HTTPResult,
} from "@antelopejs/interface-api";
class UserController extends Controller("/api/users") {
@Post("")
async createUser(@JSONBody() body: any) {
const user = await saveUser(body);
return new HTTPResult(201, user);
}
}
The first argument is the HTTP status code and the second is the response body. Use this pattern for 201 Created, 204 No Content, and other responses that are not 200.
Route prefixes and postfixes
The sections from here on are reference for extending a working endpoint. Most applications start with controllers, @Parameter(), @JSONBody(), and HTTPResult. Streaming, WebSockets, and manual registration are optional.
@Prefix and @Postfix are method decorators. A prefix runs before the main handler of a route and a postfix runs after it. Use them for authentication checks, input validation, response changes, or logging.
@Prefix(method, location?, priority?) runs before the main handler. @Postfix(method, location?, priority?) runs after the main handler.
import {
Controller,
Get,
Prefix,
Postfix,
Result,
HTTPResult,
HandlerPriority,
} from "@antelopejs/interface-api";
class ApiController extends Controller("/api") {
@Prefix("get", "status")
checkAccess() {
// Runs before the main handler for GET /api/status
// Return an HTTPResult to short-circuit the request
}
@Get("status")
async handler() {
return { version: 1 };
}
@Postfix("get", "status")
addHeaders(@Result() response: HTTPResult) {
// Runs after the main handler for GET /api/status
response.addHeader("X-API-Version", "1.0");
}
}
The method argument is the HTTP method to match, such as "get" or "post". Pass "any" to match every method. The location argument is the route path relative to the controller. The optional priority argument sets the execution order when several prefix or postfix handlers match the same route.
Handler priority
The HandlerPriority enum sets the order in which route handlers run when several handlers match the same path. It is an enum with five levels, not a decorator.
import { HandlerPriority } from "@antelopejs/interface-api";
// HandlerPriority.HIGHEST = 0
// HandlerPriority.HIGH = 1
// HandlerPriority.NORMAL = 2
// HandlerPriority.LOW = 3
// HandlerPriority.LOWEST = 4
Handlers with a lower number run first. The default priority is NORMAL. Set a priority with the last argument of @Prefix, @Postfix, @Monitor, or @Route, or with the priority field when you register a route manually.
Parameter decorators
Parameter decorators read one part of the incoming HTTP request and pass it to the handler as an argument. Each decorator reads a different part of the request.
| Decorator | Description |
|---|---|
@Parameter(name, source?) | Single value from a route parameter, the query string, or a header |
@MultiParameter(name, source?) | Multiple values from the query string or a header |
@JSONBody(limit?) | Parsed JSON request body |
@RawBody(limit?) | Raw request body as a Buffer |
@BodyStream() | Request body as a stream |
@Context() | Full RequestContext object |
@Result() | Response HTTPResult object, usually in postfix handlers |
@WriteStream(type?) | Writable stream for long-running or chunked responses |
@Connection() | WebSocket connection object, for @WebsocketHandler routes |
@Transform(fn) | Applies a function to a parameter value |
Request context
The @Context() decorator gives the handler the full request context. That context includes the raw request and response objects, the parsed URL, and other low-level details.
import {
Controller,
Get,
Context,
type RequestContext,
} from "@antelopejs/interface-api";
class DebugController extends Controller("/api/debug") {
@Get("info")
async handler(@Context() ctx: RequestContext) {
return {
method: ctx.rawRequest.method,
path: ctx.url.pathname,
};
}
}
The RequestContext interface has these fields:
rawRequest, the Node.jsIncomingMessage.rawResponse, theServerResponse.url, a parsedURLobject.routeParameters, the values of the route parameters.body, a promise of the request body.response, theHTTPResultthat the server sends.
Use @Context() when the other parameter decorators do not give you what you need. Do not return all headers or query parameters from a diagnostic endpoint, because they can contain cookies, tokens, and private data.
Streaming responses
The @WriteStream(type?) decorator passes a writable stream for long-running or chunked responses. Use it for server-sent events, file downloads, or progress updates. The type argument sets the Content-Type header and defaults to text/plain.
import { Controller, Get, WriteStream } from "@antelopejs/interface-api";
import { PassThrough } from "node:stream";
class StreamController extends Controller("/api/stream") {
@Get("data")
async streamData(@WriteStream("text/event-stream") stream: PassThrough) {
for (let i = 0; i < 10; i++) {
stream.write(`data: chunk ${i}\n\n`);
}
stream.end();
}
}
The stream stays open until you call end(). The client receives the data as the handler writes it.
@WebsocketHandler routes
The @WebsocketHandler(location?) decorator marks a method as a WebSocket handler. Its argument is the route path, so the handler below serves /ws/connect. Use the @Connection() decorator to receive the WebSocket connection object.
import {
Controller,
WebsocketHandler,
Connection,
} from "@antelopejs/interface-api";
class WebSocketController extends Controller("/ws") {
@WebsocketHandler("connect")
async handleConnection(@Connection() conn: any) {
conn.on("message", (msg: string) => {
conn.send(`Echo: ${msg}`);
});
}
}
WebSocket handlers are separate from HTTP route handlers. They manage long-lived connections that carry messages both ways.
Manual route registration
The RegisterRoute() function registers a route from code, without decorators. Use it when your routes come from configuration or other data known only at runtime.
import { Controller, RegisterRoute } from "@antelopejs/interface-api";
class HealthController extends Controller("/api") {}
RegisterRoute({
mode: "handler",
method: "get",
location: "/api/health",
callback: async () => {
return { status: "ok" };
},
parameters: [],
properties: {},
controller: HealthController,
});
RegisterRoute takes a RouteHandler object with these required fields:
mode, one of"handler","prefix","postfix","monitor", or"websocket".method, the HTTP method.location, the full route path.callback, the handler function.parameters, the computed parameter array.properties, the computed properties.controller, the controller class that declares the handler.
The optional priority field takes a HandlerPriority value. RegisterRoute throws a TypeError when the handler has no controller.
There is no @Patch decorator. For PATCH requests, use @Route("handler", "patch", location).
Starting the server
By default, the API module starts the HTTP server. You set the server port and other settings in the module's configuration in antelope.config.ts.
To decide when the server starts, set autoListen to false in the API module's configuration and call Listen() yourself:
import { defineConfig } from "@antelopejs/interface-core/config";
export default defineConfig({
name: "my-app",
modules: {
api: {
source: { type: "package", package: "@antelopejs/api", version: "1.3.4" },
config: {
servers: [{ protocol: "http", host: "127.0.0.1", port: 3000 }],
autoListen: false,
},
},
},
});
import { Listen } from "@antelopejs/interface-api";
export async function start() {
await Listen();
}
Most applications keep the default autoListen behavior. Turn it off only when the server must wait until other resources are ready.