0

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?

EDIT - following 1Ed instructions

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 !

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the details - I could get it on track !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.