Skip to content

Commit 38179a0

Browse files
Respond in JSON for URL's below API if 404
Fixes #2685.
1 parent 228b1fa commit 38179a0

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<?php declare(strict_types=1);
2+
3+
namespace App\EventListener;
4+
5+
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
6+
use Symfony\Component\HttpKernel\Event\ControllerEvent;
7+
8+
#[AsEventListener]
9+
class RespondInJsonForApiListener
10+
{
11+
public function __invoke(ControllerEvent $event): void
12+
{
13+
// For API requests, if no accept header has been set, or it is text/html or */*,
14+
// set it to application/json.
15+
16+
$request = $event->getRequest();
17+
if ($request->attributes->get('_fos_rest_zone')) {
18+
$acceptHeader = $request->headers->get('accept');
19+
20+
if (!$acceptHeader
21+
|| str_starts_with($acceptHeader, 'text/html')
22+
|| str_starts_with($acceptHeader, '*/*')) {
23+
$request->headers->set('accept', 'application/json');
24+
}
25+
}
26+
}
27+
}

0 commit comments

Comments
 (0)