boulzy / behat-api-platform-bundle
A Symfony bundle to test API Platform projects using Behat
Package info
gitlab.com/boulzy/behat-api-platform-bundle
Type:symfony-bundle
pkg:composer/boulzy/behat-api-platform-bundle
Requires
- php: ^8.3
- api-platform/json-schema: ^4.4 || ^5.0
- api-platform/metadata: ^4.4 || ^5.0
- api-platform/symfony: ^4.4 || ^5.0
- behat/behat: ^4.0
- behat/gherkin: ^4.18
- coduo/php-matcher: ^6.0.18
- friends-of-behat/symfony-extension: ^2.7
- sebastian/diff: ^6.0 || ^7.0 || ^8.0 || ^9.0
- symfony/config: ^7.4 || ^8.0
- symfony/dependency-injection: ^7.4 || ^8.0
- symfony/http-foundation: ^7.4 || ^8.0
- symfony/http-kernel: ^7.4 || ^8.0
Requires (Dev)
- ergebnis/composer-normalize: ^2.57
- friendsofphp/php-cs-fixer: ^3.95
- infection/infection: ^0.35.11
- justinrainbow/json-schema: ^6.5.2
- phpstan/extension-installer: ^1.4.3
- phpstan/phpstan: ^2.3
- phpstan/phpstan-phpunit: ^2.1.2
- phpstan/phpstan-strict-rules: ^2.1.1
- phpunit/phpunit: ^12.5 || ^13.0
- rector/rector: ^2.8.5
- shipmonk/composer-dependency-analyser: ^1.8.4
- symfony/filesystem: ^7.4 || ^8.0
- symfony/framework-bundle: ^7.4 || ^8.0
- symfony/process: ^7.4 || ^8.0
- symfony/routing: ^7.4 || ^8.0
- symfony/validator: ^7.4 || ^8.0
Suggests
- justinrainbow/json-schema: To check a response against its resource's JSON Schema, with SchemaContext
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-17 20:28:10 UTC
README
boulzy/behat-api-platform-bundle is a Symfony bundle that provides an integration between Behat and API Platform on Symfony (not on Laravel).
It gives Behat the steps to test an API Platform application in JSON-LD: send requests, then check the responses, their Hydra collections, their errors and their resource's JSON Schema.
Each request goes through the application's Symfony kernel, as Symfony's
KernelBrowser does: handle(), then terminate(), so the
kernel.terminate listeners run too. There is no HTTP server and no browser.
Between two requests, the kernel resets its services, as a worker would.
One service, Boulzy\BehatApiPlatformBundle\Client\ApiClient, holds a
scenario's headers, its cookies and its last response. Every context shares
it. The Symfony extension
reboots the kernel after each scenario, so each scenario starts with a new
client: no headers, no cookies, no variables and no response.
The bundle speaks JSON-LD, API Platform's default format. A request hook can send another one. It does not cover:
- GraphQL;
- API Platform on Laravel;
- validating a response against the API's OpenAPI document (the schema steps check it against a resource's JSON Schema);
- resetting the database between scenarios (see isolating the database).
Installation
The bundle needs PHP 8.3 or later, Symfony 7.4 or 8, Behat 4 and API Platform 4.4 or 5 on Symfony. It is a test tool: require it as a development dependency.
composer require --dev boulzy/behat-api-platform-bundle
To check the responses against their schemas, require justinrainbow/json-schema too, as for API Platform's own test assertions:
composer require --dev justinrainbow/json-schema
The bundle also installs friends-of-behat/symfony-extension,
which makes your Behat contexts Symfony services. Enable both bundles in the
test environment only:
// config/bundles.php
return [
// ...
FriendsOfBehat\SymfonyExtension\Bundle\FriendsOfBehatSymfonyExtensionBundle::class => ['test' => true],
Boulzy\BehatApiPlatformBundle\Bundle\BoulzyBehatApiPlatformBundle::class => ['test' => true],
];
The bundle has no configuration. Load the Symfony extension with your kernel, and add the bundle's contexts to your suite, next to your own:
// behat.php
use Behat\Config\Config;
use Behat\Config\Extension;
use Behat\Config\Profile;
use Behat\Config\Suite;
use Boulzy\BehatApiPlatformBundle\Context\CollectionContext;
use Boulzy\BehatApiPlatformBundle\Context\ProblemContext;
use Boulzy\BehatApiPlatformBundle\Context\RequestContext;
use Boulzy\BehatApiPlatformBundle\Context\ResponseContext;
use Boulzy\BehatApiPlatformBundle\Context\SchemaContext;
use FriendsOfBehat\SymfonyExtension\ServiceContainer\SymfonyExtension;
return (new Config())
->withProfile((new Profile('default'))
->withExtension(new Extension(SymfonyExtension::class, [
'kernel' => ['class' => App\Kernel::class, 'environment' => 'test'],
]))
->withSuite((new Suite('default'))
->withContexts(RequestContext::class, ResponseContext::class, CollectionContext::class, ProblemContext::class, SchemaContext::class)
)
);
Add only the contexts you need: each one is independent. Your own contexts
must be services of the test environment, as the Symfony extension
documents. Then write a scenario, and run vendor/bin/behat:
# features/products.feature
Feature: Products
Scenario: Creating a product
When I send a POST request to "/api/products" with the JSON:
"""
{ "name": "Chair" }
"""
Then the response status code should be 201
And the response body should match:
"""
{ "@id": "@string@", "name": "Chair", "@*@": "@*@" }
"""
Isolating the database
Each scenario starts with a new kernel, but not with a new database. Reset it the way your project prefers, for example with dama/doctrine-test-bundle, which rolls back each scenario's transaction.
Steps
Requests
RequestContext sends the requests, with the JSON-LD headers.
| Step | Sends |
|---|---|
When I send a GET request to "/products?page=2" | a request without a body |
When I send a GET request to "/products" accepting "text/csv" | the same, with this Accept header |
When I send a POST request to "/products" with the JSON: | the text block as the body |
When I send a POST request to "/products" as "text/csv": | the text block as the body, with this Content-Type |
When I send a POST request to "/media_objects" with the file "features/files/image.png" as "file" | the file as a multipart/form-data upload, in the field file; the path is relative to where Behat runs |
Given I send requests with the header "X-Tenant" set to "acme" | this header with every later request of the scenario |
Given the next request has the header "If-Match" set to "abc" | this header with the next request only |
Given I save the response's "@id" as "product" | nothing: it saves a variable |
Given I save the IRI of the response as "product" | nothing: it saves the body's @id, or else the Location header, or else Content-Location |
When two sources set the same header, the most specific one wins, from the
weakest to the strongest: the JSON-LD defaults, the request hooks,
the step's own header (such as accepting), the scenario's headers, then the
next request's.
When a response sets cookies, the client sends them back with every later request of the scenario, until a response clears them. This keeps a session open after a login request. The client ignores the cookies' path and domain.
Responses
ResponseContext checks the last response. The checks are exact: a header
must equal its whole value, and a body fails if it has a member that the step
does not expect.
| Step | Checks |
|---|---|
Then the response should be successful | the status code is 2xx |
Then the response status code should be 201 | the status code |
Then the response should have the header "Location" | the header is present |
Then the response should not have the header "X-Debug-Token" | the header is absent |
Then the response header "Location" should be "/products/1" | the header's value; a header sent several times is its values joined with , |
Then the response header "WWW-Authenticate" should be: | the same, with the value in the text block, for a value with double quotes |
Then the response media type should be "application/ld+json" | the Content-Type, without parameters such as the charset, in any case |
Then the response body should be empty | the body is empty, as for a 204 No Content |
Then the response body should be: | the body, byte for byte: {} differs from [], and \/ from / |
Then the response body should match: | the body matches the text block, a coduo/php-matcher pattern written as JSON: "@*@": "@*@" accepts extra members, "@...@" the rest of a list |
Then the response's "owner.name" should be "Alice" | the scalar at this path, read as a variable is saved: "1" stands for both the number 1 and the string "1"; to tell them apart, use the next step |
Then the response's "owner" should match: | the value at this path matches the pattern of the text block |
Then the response should not mention "password" | the text appears nowhere in the body: neither in the raw body, nor in its decoded keys and strings |
Then print the response | always passes: prints the status, the headers and the body, to debug a scenario |
A step that reads the response fails if the scenario has not sent a request yet.
When a status code check fails, the message shows the body, pretty-printed: an error's detail usually tells why. When a match fails, the message shows coduo/php-matcher's error, with the path of the failing value, and a diff of the expected and the actual values. In that diff, the parts of the pattern that match show as their actual values, so the diff only shows what failed.
Collections
CollectionContext reads the response as a Hydra collection, with or without
API Platform's hydra_prefix (hydra:member or member).
| Step | Checks |
|---|---|
Then the collection should have 3 items in total | the total of the whole collection, not of the page |
Then the collection should have 2 members | the number of members on the page |
Then the collection's "next" page should be "/products?page=2" | the IRI of a page: first, last, previous or next |
Then the collection should have no "previous" page | the collection does not link to that page |
Problems
ProblemContext reads the response as problem details
(RFC 9457), with API Platform's
violations.
| Step | Checks |
|---|---|
Then the response should be a problem with the status 422 | the status written in the body |
Then the problem's title should be "An error occurred" | the title |
Then the problem's detail should be "Not Found" | the detail |
Then the response should have the violations: | exactly these violations, in any order, from a table with the columns propertyPath and message |
Then the response should have the violations:
| propertyPath | message |
| name | This value should not be blank. |
Schemas
SchemaContext checks the response against the JSON Schema API Platform
generates for a resource's output, the same one as api-platform/test's
assertMatchesResourceItemJsonSchema(). It needs
justinrainbow/json-schema.
| Step | Checks |
|---|---|
Then the response should match the "Product" item schema | the body against the schema of the resource's first GET item operation |
Then the response should match the "Product" collection schema | the same, with its first GET collection operation |
Then the response should match the "Product" item schema of the operation "/products/{id}" | the same, with this operation |
Then the response should match the "Product" collection schema of the operation "/products" | the same, with this operation |
A resource is named by its short name, the @type of its items. An
operation is named as API Platform finds it: by its name, such as
_api_/products/{id}{._format}_get, or by its URI template, with or without
{._format}. The step fails if the operation is a collection one for an item
step, or the other way round, and if two resources share the short name.
The schema follows the format of the response, from its Content-Type:
JSON-LD gets the Hydra schema, and each other format its own. A media type
that is none of api_platform.formats fails the step.
When the body does not match, the message lists each violation with its
path ((root) for the whole body):
The response does not match the "Product" item schema:
- name: The property name is required
Variables and paths
Given I save the response's "@id" as "product" saves the value at this path.
A string is saved as it is, and any other scalar as JSON: the number 1 is
saved as 1, true as true.
Later steps write the variable {{product}}: in a path and its query string,
a header, a request body or an expected text.
When I send a POST request to "/products" with the JSON:
"""
{ "name": "Chair" }
"""
And I save the IRI of the response as "product"
When I send a GET request to "{{product}}"
Then the response body should match:
"""
{ "@id": "{{product}}", "name": "Chair", "@*@": "@*@" }
"""
In a JSON text, a variable is escaped as in a JSON string, so a value with a
double quote or a backslash keeps the JSON valid. A variable is inserted as
text: a value that looks like a coduo/php-matcher pattern, such as
@string@, acts as a pattern. A step that uses a variable the scenario has
not saved fails.
A path is a list of keys separated by dots: "@id", "owner.name", or
"tags.0.name" for the name of the first tag.
JSON-LD and other formats
Each request has the media types API Platform expects in JSON-LD:
| Method | Accept | Content-Type |
|---|---|---|
GET, HEAD, OPTIONS | application/ld+json | none |
PATCH | application/ld+json | application/merge-patch+json |
any other: POST, PUT, DELETE… | application/ld+json | application/ld+json |
The requests go to http://localhost.
Other formats
To send another format, implement a request hook that sets
its media types. For example, for JSON:API, enabled in api_platform.formats:
use Boulzy\BehatApiPlatformBundle\Client\RequestHook;
use Symfony\Component\HttpFoundation\Request;
final class JsonApiMediaTypes implements RequestHook
{
public function beforeSend(Request $request): void
{
$request->headers->set('Accept', 'application/vnd.api+json');
if (!\in_array($request->getMethod(), ['GET', 'HEAD', 'OPTIONS'], true)) {
$request->headers->set('Content-Type', 'application/vnd.api+json');
}
}
}
The request and response steps work with any JSON body. The collection and
problem steps, and the @id of "I save the IRI", read JSON-LD only: for
another format, write your own steps.
Request hooks
Implement Boulzy\BehatApiPlatformBundle\Client\RequestHook as a service of
your application. With autoconfiguration, it needs nothing else: the client
calls every hook's beforeSend() for each request, after the JSON-LD headers
and before the headers the steps set. That is the place to sign the requests
in:
use Boulzy\BehatApiPlatformBundle\Client\RequestHook;
use Symfony\Component\HttpFoundation\Request;
final class TestAuthenticator implements RequestHook
{
private ?string $user = null;
// Called by a step of yours: Given I am signed in as "alice".
public function signIn(string $user): void
{
$this->user = $user;
}
public function beforeSend(Request $request): void
{
if (null !== $this->user) {
// However your application authenticates: a token, a cookie, a signature…
$request->headers->set('Authorization', 'Bearer '.$this->tokenFor($this->user));
}
}
}
To sign in with a cookie, set it in $request->cookies: that is where the
application reads it. For an application that checks the host, set it the
same way: $request->headers->set('Host', 'api.example.com').
Writing your own steps
The bundle's steps are deliberately plain: exact checks, in JSON-LD. For anything your project needs on top, write the step in a context of your own. The bundle's contexts are final, but their building blocks are services you can inject by autowiring:
| Service | Gives |
|---|---|
Boulzy\BehatApiPlatformBundle\Client\ApiClient | the scenario's requests and its last response, the same ones the bundle's contexts use: send(), response(), body() |
Boulzy\BehatApiPlatformBundle\Client\Variables | the scenario's variables: set() saves one, replace() and replaceInJson() fill them in a text |
Boulzy\BehatApiPlatformBundle\Matcher\JsonMatcher | a coduo/php-matcher match, assertMatches(), with the same failure message and diff as the bundle's steps |
JsonPath's static helpers read a response body: decode() the whole of it,
value() the value at a path, read() the same as a string, as the save step
does, and find() the first of several keys in a decoded value.
For example, a step that matches a body without its JSON-LD keywords, so a
pattern needs no @context, @id or @type:
use Behat\Behat\Context\Context;
use Behat\Gherkin\Node\PyStringNode;
use Behat\Step\Then;
use Boulzy\BehatApiPlatformBundle\Client\ApiClient;
use Boulzy\BehatApiPlatformBundle\Client\JsonPath;
use Boulzy\BehatApiPlatformBundle\Client\Variables;
use Boulzy\BehatApiPlatformBundle\Matcher\JsonMatcher;
final class ApiContext implements Context
{
public function __construct(
private readonly ApiClient $client,
private readonly Variables $variables,
private readonly JsonMatcher $matcher,
) {
}
#[Then('the response body should match, without JSON-LD keywords:')]
public function theResponseBodyShouldMatchWithoutKeywords(PyStringNode $pattern): void
{
$this->matcher->assertMatches(
self::withoutKeywords(JsonPath::decode($this->client->body())),
\json_decode($this->variables->replaceInJson($pattern->getRaw()), true, flags: \JSON_THROW_ON_ERROR),
);
}
private static function withoutKeywords(mixed $value): mixed
{
if (!\is_array($value)) {
return $value;
}
// A list's keys are positions: only its items lose keywords.
if (!\array_is_list($value)) {
unset($value['@context'], $value['@id'], $value['@type']);
}
return \array_map(self::withoutKeywords(...), $value);
}
}
send() fills in the variables of the path and the headers. It sends the
body as it is: call $this->variables->replaceInJson($body) first to fill in
a JSON body.
Contributing
You need Docker and Task:
task install, then task qa and task test before each push. docs/development.md
explains the checks, the tests and the pipeline, and AGENTS.md the rules every contributor follows.
License
This project is licensed under the MIT License.