Use JSON instead HTML for access denied on some custom paths 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.
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.