Requesting a JSON response with the Symfony HTTP test client
Published on 2020-11-24 • Modified on 2020-11-24
In this snippet, we will see how to request a JSON response with the Symfony HTTP test client. If your controller returns in a JSON response, there is nothing special to do as the response will always be JSON. But when using API Platform, the returned format can vary as it can be JSON, JSON+LD, HTML... In this case, you must specify the format you want to get. This is done by passing the accept HTTP header. The trick here is that Symfony transforms the keys with the HTTP_*
pattern to header keys. In this case, the header that is sent is accept: application/ld+json
. There is another trick with API Platform; you can force the requested format by specifying the extension; therefore, you don't have to pass the accept header. This snippet is to show how to do with with the base Symfony WebTestCase
because one could use the ApiTestCase
provided by API Platform which handles all this for you and also provides several useful additional assertions specific to API testing.
<?php
declare(strict_types=1);
namespace App\Tests\Functional\Entity;
use App\Tests\WebTestCase;
/**
* For better tests use the ApiTestCase provided by API Platform.
*
* @see https://api-platform.com/docs/distribution/testing/#writing-functional-tests
* @see ApiTestCase
*/
final class ArticleTypeTest extends WebTestCase
{
public function testArticleTypeCollection(): void
{
$client = self::createClient();
$client->request('GET', '/api/articles.jsonld');
self::assertResponseIsSuccessful();
self::assertResponseHeaderSame('content-type', 'application/ld+json; charset=utf-8');
$client->request('GET', '/api/articles', [], [], ['HTTP_ACCEPT' => 'application/ld+json']);
self::assertResponseIsSuccessful();
self::assertResponseHeaderSame('content-type', 'application/ld+json; charset=utf-8');
}
}
More on Stackoverflow Read the doc More on the web Random snippet