Skip to content
LykosJSLYKOSJS
CreatorDeveloperBenchmarkshomeGet started
v1.0.0
Application & serverREST APIGraphQLRouting & groupsRequest context & repliesValidationError handling
PREVIOUSApplication & serverNEXT GraphQL
© 2026 LykosJS · MIT LicenseBun · TypeScript

© 2026 LykosJS. Released under the MIT License.
Built by Zen Allaham.

DocsGitHubX
DOCS/V1.0.0/CORE CONCEPTS
CORE CONCEPTS

REST API

Build structured REST APIs with modules, routers, controllers, services, authentication, middleware and validation schemas.

Understanding the REST architecture

LykosJS provides a module-oriented REST architecture that separates HTTP routing, request handling, business logic and dependency management. Instead of placing every operation inside route handlers, the REST starter organizes features into dedicated classes.

A typical REST feature follows this structure:

ts
1UsersModule2  ├── UsersRouter3  ├── UsersController4  ├── UsersService5  ├── UserSchema6  └── rules/7      ├── create.ts8      └── update.ts

Each layer has a specific responsibility:

  • Module — declares dependencies, providers, controllers, routers and authentication configuration.
  • Router — registers HTTP methods, paths and route-level middleware.
  • Controller — handles incoming requests and coordinates feature operations.
  • Service — contains reusable business operations.
  • Schema — represents a database's schema definition.
  • Rules — defines validation schemas for incoming data.

How a REST request flows

A request enters the HTTP server, matches a registered route and passes through its middleware pipeline before reaching the route handler. In the REST architecture, the router connects that request to a controller method, which delegates operations to a service.

LykosJS REST request flow
  • The HTTP server receives the incoming request.
  • The router matches the HTTP method and URL path.
  • Global, group and route-level middleware execute through the middleware pipeline.
  • The controller handles the request and coordinates the operation.
  • The service performs the requested business operation.
  • The controller returns a Response to the client.

1. Modules: organize REST features

Modules are the main organizational unit of a LykosJS application. A module declares which classes belong to a feature and how they participate in dependency injection.

The REST starter uses DIModule to define feature modules. For example, a users module can register its service, controller and router:

ts
1import {2  AuthMiddleware,3  bind,4  defineAuth,5  Lykos,6  DIModule,7} from 'lykosjs'8 9import { UsersService } from './users.service'10import { UsersController } from './users.controller'11import { UsersRouter } from './users.route'12 13export class UsersModule extends DIModule {14  override imports = []15 16  override providers = [UsersService]17 18  override controllers = [bind(UsersController, UsersService)]19 20  override routers = [bind(UsersRouter, Lykos, UsersController, AuthMiddleware)]21 22  override auth = defineAuth({ verifier: UsersController, mode: 'bearer' })23}

The module uses several registration properties:

  • imports — modules required by this module.
  • providers — classes registered as dependency injection providers.
  • controllers — controller classes and their dependencies.
  • routers — router classes responsible for registering routes.
  • auth — authentication configuration for the module.

The bind() helper describes the dependencies required by a class. The module loader resolves these dependencies when loading the module and registers its router.

The defineAuth() configuration in this example declares a bearer authentication mode and uses UsersController as its verifier.

Keep features independent
Create separate modules for independent application features. This keeps their providers, controllers, routers and authentication configuration organized.

2. Routers: define HTTP endpoints

A router class connects HTTP endpoints to controller methods. It is responsible for defining paths, HTTP methods and middleware, rather than implementing business operations.

The REST starter uses the Lykos instance, a controller and an authentication middleware as dependencies of its router.

ts
1import type { Lykos } from 'lykosjs'2import { AuthMiddleware } from 'lykosjs'3import { UsersController } from './users.controller'4 5export class UsersRouter {6  constructor(7    private readonly app: Lykos,8    private readonly controller: UsersController,9    private readonly authMiddleware: AuthMiddleware,10  ) {}11 12  register(): void {13    // Public routes14    this.app.group('/api/users', (guest) => {15      guest.GET('/', this.controller.findAll)16      guest.GET('/:id', this.controller.findOne)17    })18 19    // Protected routes20    this.app.group(21      '/api/users',22      (auth) => {23        auth.POST('/', this.controller.create)24        auth.PUT('/:id', this.controller.update)25        auth.DELETE('/:id', this.controller.delete)26      },27      this.authMiddleware.middleware,28    )29  }30}

This example separates user endpoints into two groups:

  • Public endpoints: retrieving all users and retrieving a user by ID.
  • Protected endpoints: creating, updating and deleting users.

The group() method applies a shared URL prefix to the routes registered inside its callback. Middleware passed as the third argument is included in the registered routes' middleware pipeline.

The route parameter :id represents a dynamic URL segment. It is available through the request context's params object.

Keep routers focused
Routers should describe how requests reach controllers. Keep business operations out of router registration code.

3. Controllers: handle requests

Controllers are responsible for handling incoming requests. They receive the request context and reply object, then call the appropriate service method.

In the REST starter, controller handlers are defined as properties typed with ContextHandler. This allows them to be passed directly to router registration methods.

ts
1import type { ContextHandler } from 'lykosjs'2import type { UsersService } from './users.service'3 4export class UsersController {5  constructor(6    private readonly usersService: UsersService,7  ) {}8 9  readonly create: ContextHandler = async (ctx, reply) => {10    const result = await this.usersService.create()11 12    // Return a Response after implementing the operation.13  }14 15  readonly findAll: ContextHandler = async (ctx, reply) => {16    const result = await this.usersService.findAll()17 18    // Return a Response after implementing the operation.19  }20 21  readonly findOne: ContextHandler = async (ctx, reply) => {22    const result = await this.usersService.findOne()23 24    // Return a Response after implementing the operation.25  }26 27  readonly update: ContextHandler = async (ctx, reply) => {28    const result = await this.usersService.update()29 30    // Return a Response after implementing the operation.31  }32 33  readonly delete: ContextHandler = async (ctx, reply) => {34    const result = await this.usersService.delete()35 36    // Return a Response after implementing the operation.37  }38}

A controller can access request information through ctx and construct responses through reply. For example, the context exposes request parameters, query parameters, headers and request body parsing methods.

ts
1// Read a dynamic route parameter2const userId = ctx.params.id3 4// Read a query parameter5const page = ctx.query.get('page')6 7// Parse a JSON request body8const body = await ctx.json<{9  name: string10  email: string11}>()12 13// Return a successful response14return reply.OK({15  message: 'Users retrieved successfully',16  data: result,17})

These are the available request and response interfaces. The actual business logic and response structure are defined by your application.

Handlers must return a Response
Every route handler must return a standard Response object. Calling a service and assigning its result to a variable is not enough. Returning undefined or a plain object results in an HTTP 500 response.

4. Services: isolate business logic

Services contain the operations used by controllers. They help keep business logic separate from HTTP request handling and allow operations to be reused across different parts of an application.

The REST starter generates a service class with common CRUD operation placeholders:

ts
1export class UsersService {2  constructor() {}3 4  async create() {5    // Implement creation logic.6  }7 8  async findAll() {9    // Implement fetching all records.10  }11 12  async findOne() {13    // Implement fetching a record by ID.14  }15 16  async update() {17    // Implement updating a record.18  }19 20  async delete() {21    // Implement deleting a record.22  }23}

These methods are starter placeholders. You implement their actual operations, such as interacting with a database or applying business rules.

Controllers call these methods through constructor injection. This keeps the controller independent of the service's internal implementation.

5. Authentication and protected routes

The REST starter can configure authentication at the module level using defineAuth(). In the users example, the module declares bearer authentication and identifies the controller used as the token verifier.

ts
1override auth = defineAuth({ verifier: UsersController, mode: 'bearer' })

The router receives AuthMiddlewarethrough dependency injection and applies its middleware property to protected route groups.

ts
1this.app.group(2  '/api/users',3  (auth) => {4    auth.POST('/', this.controller.create)5    auth.PUT('/:id', this.controller.update)6    auth.DELETE('/:id', this.controller.delete)7  },8  this.authMiddleware.middleware,9)

The controller exposes a verifyToken()method in the starter as the verifier entry point. You must implement the token verification logic for your application's authentication system.

Authentication requires implementation
The generated starter provides the authentication configuration and middleware wiring. Token verification is still an application responsibility when the generated verifier contains a TODO placeholder.

6. Validation schemas

LykosJS provides defineSchema() andValidator for defining validation rules. The REST starter separates create and update rules into dedicated files.

A create-user schema can define rules for individual fields:

ts
1import { defineSchema, Validator } from 'lykosjs'2 3export const CreateUserRule = defineSchema({4  name: Validator.string(3, 50).required(),5  email: Validator.string(3, 255).email().required(),6  password: Validator.string(8, 40).required().confirmed(),7})

The available examples demonstrate these validation operations:

  • Validator.string(min, max) — define string length constraints.
  • .required() — mark a field as required.
  • .email() — apply email validation.
  • .confirmed() — enable the confirmed validation rule.

You can reuse the create schema when defining update rules:

ts
1import { CreateUserRule } from './create'2 3export const UpdateUserRule = CreateUserRule

This example exports the same schema under a separate update-rule name. If your update operation requires different validation rules, define a separate schema instead.

Define rules and apply them
A schema definition describes validation rules. The generated starter's commented examples do not demonstrate automatic validation inside controllers. Make sure your request-handling flow actually applies the schema before relying on its rules.

7. Schema organization

The starter also provides a dedicated schema file for feature-level data definitions. For example:

ts
1export class UserSchema {}

This generated class is currently empty. You can use the file as the starting point for your own user-related schema implementation. The actual database model and persistence behavior depend on the implementation you add.

8. Testing controllers and services

The REST starter includes tests written with bun:test. Its initial tests verify that controller and service instances can be created and that their expected methods are available.

A controller test can instantiate the controller with its service dependency:

ts
1import { describe, expect, test } from 'bun:test'2import { UsersController } from '../users.controller'3import { UsersService } from '../users.service'4 5describe('UsersController', () => {6  const usersController = new UsersController(7    new UsersService(),8  )9 10  test('should be defined', () => {11    expect(usersController).toBeDefined()12  })13 14  test('should expose all route handlers', () => {15    expect(typeof usersController.create).toBe('function')16    expect(typeof usersController.findAll).toBe('function')17    expect(typeof usersController.findOne).toBe('function')18    expect(typeof usersController.update).toBe('function')19    expect(typeof usersController.delete).toBe('function')20  })21})

The service test follows the same approach, checking that the service instance and its CRUD methods exist. These generated tests are basic structure checks, not complete tests of database operations, authentication or request validation.

Run the project's tests with:

bash
1bun test

9. Register application modules

After defining your feature modules, collect them in a central module registry. This makes it easier to load the application's features from one place.

ts
1import { UsersModule } from './modules/users/users.module'2 3export const Modules = [UsersModule]

The application entry point creates the Lykos instance, registers modules and starts the server.

ts
1import { Lykos } from 'lykosjs'2import { Modules } from './modules'3 4async function launch() {5  const app = new Lykos()6 7  app.GET('/', async (ctx, reply) => reply.send('Welcome to LykosJS 🐺'))8 9  app.modules(Modules)10 11  app.listen(4000, () => console.log('🐺 LykosJS is running at http://localhost:4000'))12}13 14launch().catch((error: unknown) => {15  console.error('🐺 [LykosJS] Failed to start application:', error)16  process.exit(1)17})

Calling app.modules(Modules) loads the declared modules, resolves their dependencies and registers their routers. The server starts afterward with app.listen().

10. REST starter development workflow

The generated project provides the initial structure, but the feature implementation remains yours. A typical development workflow looks like this:

  • Generate a REST project using the LykosJS CLI.
  • Define the feature module and register its dependencies.
  • Create router endpoints and organize public and protected routes.
  • Implement controller handlers and their response handling.
  • Implement service methods and business operations.
  • Define validation rules for incoming data.
  • Configure authentication and implement token verification when required.
  • Write tests for the implemented behavior.
  • Register the modules and start the application.

REST architecture best practices

  • Keep route registration inside router classes.
  • Keep request handling and response construction inside controllers.
  • Keep reusable business operations inside services.
  • Use modules to organize feature dependencies.
  • Apply authentication middleware only to routes that require protection.
  • Define validation rules separately from controller implementation.
  • Always return a valid Response from route handlers.
  • Test actual feature behavior in addition to checking that classes and methods exist.
Start small, scale by feature
You do not need to create a module, router, controller and service for every small endpoint. Use inline handlers for simple routes, then introduce the REST structure as your application grows.