Skip to main content
The @api decorator automatically converts Model methods into HTTP API endpoints. Adding the decorator to a method auto-generates routing, type validation, and client code.

Basic Usage

What gets generated:
  • HTTP endpoint: GET /user/findById?id=1
  • TypeScript client function
  • TanStack Query hooks (when selected)
  • API documentation

Decorator Options

All Options

httpMethod

Specifies the HTTP method.
Default: If httpMethod is omitted, GET is the default.

clients

Specifies which client code types to generate.
Generated client code:
Default: If clients is omitted, ["axios"] is the default.

path

Specifies a custom API path.
Path parameters:
If path is omitted, it’s auto-generated in /{model}/{method} format.
  • Model: UserModeluser
  • Method: findByIdfindById
  • Result: /user/findById

resourceName

Specifies the API resource name. Used in TanStack Query’s queryKey.
Naming guide:

guards

Sets up authentication and permission checks.
Guard types:
Guard logic is defined in guardHandler in sonamu.config.ts.
sonamu.config.ts

contentType

Specifies the response Content-Type.

timeout

Specifies API timeout in milliseconds.
Timeout is a client-side setting. The server may continue executing, so you may need to set server-side timeout separately.

cacheControl

Sets HTTP Cache-Control headers.
CacheControl options:

compress

Controls response compression settings.

Combining Multiple Decorators

@api + @transactional

Execute API within a transaction.

@upload (Standalone)

Creates a file upload API. @upload is used independently without @api.
Upload options: Single/multiple file handling is determined by how you access bufferedFiles from the context.

API Path Rules

Default paths are generated with the following rules:
Conversion rules:
  • Model name: PascalCase → camelCase
    • UserModeluser
    • BlogPostModelblogPost
  • Method name: Used as-is
    • findByIdfindById
Examples:

Practical Examples

Basic CRUD API

Authentication API

Sonamu handles authentication through better-auth’s HTTP endpoints. For login (/api/auth/sign-in/email), logout (/api/auth/sign-out), and other auth operations, use the endpoints provided directly by better-auth rather than Sonamu @api decorated methods.
The me() API that returns the current logged-in user’s information is implemented via context.user.

Next Steps

Business Logic

Learn business logic writing patterns

Stream Decorator

Send real-time events with @stream

Upload Decorator

Handle file uploads with @upload

Guards

Implementing authentication and authorization