@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
- 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.clients
Specifies which client code types to generate.path
Specifies a custom API path.If path is omitted, it’s auto-generated in
/{model}/{method} format.- Model:
UserModel→user - Method:
findById→findById - Result:
/user/findById
resourceName
Specifies the API resource name. Used in TanStack Query’s queryKey.guards
Sets up authentication and permission checks.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.cacheControl
Sets HTTP Cache-Control headers.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.
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:- Model name: PascalCase → camelCase
UserModel→userBlogPostModel→blogPost
- Method name: Used as-is
findById→findById
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.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