Sparse fieldsets
Edit on GitHubSparse fieldsets let API consumers request only the attributes they need from a resource. This reduces response payload size, improves performance, and follows the JSON:API sparse fieldsets specification.
Query syntax
Use the fields query parameter with the resource type as the key and a comma-separated list of attribute names as the value:
?fields[RESOURCE_TYPE]=attribute1,attribute2
The resource type corresponds to the shortName of the API Platform resource (in kebab-case for JSON:API).
Examples
Request specific attributes
To retrieve only the name and locale attributes from the stores resource:
GET /stores?fields[stores]=name,locale
Accept: application/vnd.api+json
Response:
{
"data": [
{
"id": "1",
"type": "stores",
"attributes": {
"name": "DE",
"locale": "de_DE"
}
}
]
}
Without sparse fieldsets, the same request returns all attributes defined on the resource.
Combine with relationships
Sparse fieldsets work together with the include parameter. You can filter attributes on both the main resource and included relationships:
GET /customers/customer--1?include=addresses&fields[customers]=email,firstName&fields[customers-addresses]=city,zipCode
Accept: application/vnd.api+json
Response:
{
"data": {
"id": "customer--1",
"type": "customers",
"attributes": {
"email": "[email protected]",
"firstName": "John"
},
"relationships": {
"addresses": {
"data": [
{ "type": "customers-addresses", "id": "1" }
]
}
}
},
"included": [
{
"id": "1",
"type": "customers-addresses",
"attributes": {
"city": "Berlin",
"zipCode": "10115"
}
}
]
}
Combine with pagination
Sparse fieldsets work with paginated collections:
GET /customers?fields[customers]=email&page=1&itemsPerPage=5
Accept: application/vnd.api+json
How it works
Sparse fieldsets are enabled globally for all API Platform resources. The processing chain works as follows:
- Request parsing: The
JsonApiProviderparsesfields[]query parameters and stores them as_api_filter_propertyon the request. - Filter invocation: The
SerializerFilterContextBuilderreads the operation’s registered filters and invokes each one. - Property filtering: The
PropertyFilterreads_api_filter_propertyand setsAbstractNormalizer::ATTRIBUTESon the serializer context. - Serialization: The Symfony serializer only includes the listed attributes in the response.
No changes to providers, processors, or resource schemas are required. Sparse fieldsets work automatically for all resources.
Notes
- If no
fieldsparameter is provided, all attributes are returned as usual. - The
idandtypefields in JSON:API responses are always included regardless of thefieldsparameter. - Requesting a nonexistent attribute name silently excludes it from the response without causing an error.
Thank you!
For submitting the form