0

I create a small API for one project using Bathic Authentication. The API consists of some custom paths defined in routes in a custom module. Using JsonResponse() in the controller we send back a JSON object with data.

But in case the user does not have permissions to access the path the route gives back the 404 HTML page. How can I tell Drupal to return a JSON object for my API paths under every circumstances?

Another example: we defined just to accept GET in the route. Using POST will return a HTML error page - we want Drupal to send back JSON with error information.

1

Drupal returns the 404 in the format requested, so adding the query string ?_format=json to the request should return a JSON response under any circumstances. If Drupal doesn't detect the format it uses HTML by default. You could either help Drupal detecting the format in a request subscriber or implement an exception subscriber to return JSON exceptions similar to ExceptionJsonSubscriber::on4xx for your API paths.

  • Unfortunately sometimes ?_format=json gives a strange error back (somethinkg like "format json unknown/ not allowed"). Could you help me with describing an event subscriber which handles returning always JSON on some paths? – Tobias Krause Jun 8 '18 at 11:42
  • You could copy or extend the mentioned ExceptionJsonSubscriber, increase the priority and add html to the handled format or empty the formats to handle all. Then check in the event listener for the path and return a json response. – 4k4 Jun 8 '18 at 12:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.