1

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 Answer 1

2

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.

3
  • 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? Commented Jun 8, 2018 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.
    – 4uk4
    Commented Jun 8, 2018 at 12:09
  • @TobiasKrause With _format=json, the route needs to accept JSON as format, or Drupal will throw an error saying the format is not allowed. That is understandable, as you cannot request to output JSON to a route returning HTML markup.
    – avpaderno
    Commented Aug 8, 2020 at 10:59

Your Answer

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

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