Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions webapp/src/EventListener/RespondInJsonForApiListener.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php declare(strict_types=1);

namespace App\EventListener;

use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpKernel\Event\ControllerEvent;

#[AsEventListener]
class RespondInJsonForApiListener
{
public function __invoke(ControllerEvent $event): void
{
// For API requests, if no accept header has been set, or it is text/html or */*,
// set it to application/json.

$request = $event->getRequest();
if ($request->attributes->get('_fos_rest_zone')) {
$acceptHeader = $request->headers->get('accept');

if (!$acceptHeader
|| str_starts_with($acceptHeader, 'text/html')
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this allowed by the specs? I think if someone explicit requests text/html only we should still return text/html.
Can we do the alternative of when the acceptHeader contains app/json or is */* set it to app/json only?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To me it's annoying if you open a wrong api in your browser you don't get json.
Seeks an n=1 test with GitHub also returns json: https://api.github.com/bla

|| str_starts_with($acceptHeader, '*/*')) {
$request->headers->set('accept', 'application/json');
}
}
}
}
Loading