JSON Router
JSON Router
The JSON router allows you to define routes in a JSON file, providing a flexible and dynamic way to configure routes. This method is useful for applications requiring dynamic route definitions from external configurations.
routes.json
Define routes in a routes.json file in the application config directory. The file contains an array of route objects, each specifying the following properties:
route: The URL pattern.controller: The controller class name.action: The controller method name.method(optional): A single HTTP method to match, as a string (for example"GET"). Defaults toGETwhen neithermethodnormethodsis specified.methods(optional): Multiple HTTP methods to match, as an array (for example["GET", "POST"]). Takes precedence overmethodwhen both are present.args(optional): An array of default arguments passed to the action. A numeric array is passed by position; an associative object is passed by name. See Default Values.responseType(optional): The expected response type.middleware(optional): One or more middleware class names or aliases to apply to the route.
Example routes.json file:
[
{
"route": "/api/v1/product/list",
"controller": "Application\\Controller\\Product",
"action": "list",
"method": "GET"
},
{
"route": "/api/v1/product/{int:id}",
"controller": "Application\\Controller\\Product",
"action": "getProduct",
"method": "GET"
},
{
"route": "/api/v1/product/{int:id}",
"controller": "Application\\Controller\\Product",
"action": "saveProduct",
"methods": ["POST", "PUT"]
}
]Loading Routes
To load the JSON routes, add the following configuration to the app.php file:
<?php
return [
'development' => [
'router' => [
'type' => 'json',
'file' => 'routes.json',
],
],
];The file key specifies the path to the JSON file containing the route definitions.
Tips
The JSON router supports route parameters and response types, similar to the file router.
For route parameters, custom matchers, default values, response types, and middleware, see the routing overview.