I am building a json api. Formats are managed nicely via the routing.yml configuration file:
user_info:
url: /users/:user_id
class: sfRequestRoute
param: { module: user, action: details, sf_format: json }
requirements:
user_id: \d+
sf_method: [GET]
Now I would like to make sure that any request that is sent to my app will return a result in json format (example: "/dummy" should return an error in json). I am getting on track with the following default route at the end of the same file:
default:
url: /*
param: { sf_format: json }
When I route to an inexisting page or module, this renders correctly a json... Error! The html page generated was a 404, now with this routing I get a 500 (server error). How can I keep a similar behaviour as the one I had in the default html page, just changing the rendering into a json output?
So I edited my factories.yml, created a default module in my api project, there in my default actions added the executeError404 function mentioned below... Then I Set up the corresponding Error404Success.php page...
For some reason, I still need the routes, which I modified to avoid the :module and :action keywords:
default_index:
url: /:a
default:
url: /:a/:b/*
And here there I am ! My 404 page comes in json format for the whole api :) Thanks a lot !
This default route will execute the index
action of the default
module (by default). You should add a indexSuccess.json.php
template file to the default module or modify the default/index
action to return a json response early.
If you just want to return a 404 every time if this default route matches you can change the default action to error404
in factories.yml
:
all:
routing:
class: sfPatternRouting
param:
generate_shortest_url: true
extra_parameters_as_query_string: true
default_action: error404
Or you can set the request format of the default 404 action explicitly to json like this
public function executeError404(sfWebRequest $request)
{
$request->setRequestFormat('json');
}
and you can remove the default route.
I recommend NOT to use these kind of default routes as they make really hard to keep track of all possible URL-s to the site. You should create a separate route for each particular action or use route collections.