Generating Controllers
The fastest way to create a new controller is using the Kit CLI:- Create
src/controllers/user.rswith a controller stub - Update
src/controllers/mod.rsto export the new controller
Controller Structure
Controllers are async functions decorated with#[handler] that take a Request and return a Response:
The Handler Attribute
All controller methods use the#[handler] attribute. This enables:
- Automatic extraction and validation of request data
- Clean integration with FormRequests for POST data validation
- Future DX improvements like dependency injection
#[handler]: Required attribute that enables automatic parameter extractionasync fn: Controllers are asynchronous, allowing non-blocking I/O operationsRequest: Contains all information about the incoming HTTP requestResponse: An alias forResult<HttpResponse, HttpResponse>, enabling the?operator
For handling POST data with validation, see Requests.
Path Parameter Injection
The#[handler] macro supports automatic extraction of path parameters directly as function arguments. This eliminates the need to manually call req.param().
Primitive Path Parameters
Declare path parameters as function arguments with primitive types:Multiple Path Parameters
Extract multiple parameters in a single handler:Supported Types
The parameter name in your function must match the route parameter name (e.g.,
{id} requires id: i32).Route Model Binding
Route model binding automatically resolves database models from route parameters. If the model is not found, Kit automatically returns a 404 response.Setting Up Route Binding
First, enable route binding for your model using theroute_binding! macro:
Using Route Model Binding in Handlers
Now you can directly accept the model as a handler parameter:Combining Models with Form Requests
Mix route model binding with form requests for update operations:Error Responses
Flexibility
You have full control over how you access route parameters:The Request Object
TheRequest struct provides Laravel-like access to request data:
Getting Route Parameters
Access dynamic URL segments defined in your routes:Getting Headers
Access HTTP headers from the request:Request Methods
Creating Responses
Controllers return responses using helper methods and macros:JSON Responses
Text Responses
Setting Status Codes
For more response options, see the Responses documentation.
RESTful Controllers
Kit encourages organizing controllers following REST conventions:Error Handling in Controllers
Use the? operator for clean error propagation:
For more error handling options, see the Responses documentation.
Dependency Injection
UseApp::resolve() to inject dependencies from the container: