Skip to main content
The @api decorator automatically transforms Model class methods into HTTP API endpoints.

Decorator Overview

Automatic Routing

Transform methods to APIs Auto-generate URLs

Type Safety

Parameter type validation Compile-time checks

HTTP Methods

GET, POST, PUT, DELETE RESTful API support

Error Handling

Automatic error conversion Consistent response format

Basic Usage

Simplest Form

Generated endpoint:
  • URL: GET /api/user/getUser
  • Parameters: { id: number }
  • Response: User object

Specifying HTTP Methods

API Routing Rules

URL Generation Pattern

URL Rules: - Base path: /api/{modelName}/{methodName} - modelName is converted to lowercase
  • Example: UserModel.getProfile/api/user/getProfile

Parameter Handling

Single Parameter

Complex Parameters (Objects)

Multiple Parameters

Return Types

Basic Types

Structured Response

Decorator Combinations

@api + @transactional

@api + cacheControl/compress Options

You can control caching and compression of API responses directly from the @api decorator.

Cache-Control Configuration

Cache-Control Options:
  • maxAge: Browser cache duration (seconds)
  • sMaxAge: CDN/proxy cache duration (seconds)
  • staleWhileRevalidate: Stale state allowance duration (seconds)
  • public: Public cache flag (default: true)
  • private: Private cache (per-user)
Preset Strings:
  • Time unit strings like "1m", "5m", "1h", "1d" can be used

Compression Configuration

Compression Options:
  • true: Compress response with gzip/deflate
  • false: Disable compression (default)

Combined Usage

Practical Example: API Optimization:
Performance Tips:
  • Use cacheControl for static or infrequently changing data
  • Use compress: true for responses larger than 10KB
  • Use { private: true, maxAge: 0 } to prevent caching of private data
Caution: - compress: true increases CPU usage (inefficient for small responses) - Excessively long cache durations can delay update propagation - private: true disables CDN caching

Error Handling

Automatic Error Conversion

By default, all errors are converted to HTTP 500. For custom error handling, you need to implement a separate error handler.

Practical Examples

CRUD API

Complex Business Logic

Type Safety

Parameter Type Validation

Explicit Return Types

Cautions

Cautions when using @api: 1. Only usable in Model classes 2. Method must be async function 3. modelName property is required 4. Specifying parameter/return types is recommended 5. Propagate errors with throw

Common Mistakes

Next Steps

HTTP Methods

GET, POST, PUT, DELETE details

Parameters

Type definitions and validation

Return Types

Defining response types

Error Handling

API error handling