首页
/ API Platform Laravel 中实现 JSON:API 规范的查询参数支持

API Platform Laravel 中实现 JSON:API 规范的查询参数支持

2025-07-01 12:21:31作者:凤尚柏Louis

JSON:API 是一种流行的 API 规范,它不仅定义了请求和响应体的格式,还规范了查询参数的使用方式。在 API Platform Laravel 中,我们可以通过配置来实现完整的 JSON:API 查询参数支持,包括排序、分页和过滤等功能。

JSON:API 查询参数规范概述

JSON:API 规范为 API 查询定义了三种主要的参数类型:

  1. 排序参数:使用 sort 参数,支持多字段排序和降序排序
  2. 分页参数:使用 page 前缀,支持多种分页方式
  3. 过滤参数:使用 filter 前缀,提供灵活的查询能力

在 API Platform Laravel 中启用 JSON:API 查询参数

基本配置

在 Laravel 项目中,我们需要在 config/api-platform.php 文件中进行全局配置:

use ApiPlatform\Metadata\QueryParameter;
use ApiPlatform\JsonApi\Filter\SparseFieldset;
use ApiPlatform\Laravel\Eloquent\Filter\JsonApi\SortFilter;

return [
    'parameters' => [
        new QueryParameter(key: 'fields', filter: SparseFieldset::class),
        new QueryParameter(key: 'sort', filter: SortFilter::class),
    ],
];

资源级别配置

如果需要对特定资源进行更精细的控制,可以在资源类上使用注解:

use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\QueryParameter;
use ApiPlatform\JsonApi\Filter\SparseFieldset;
use ApiPlatform\Laravel\Eloquent\Filter\JsonApi\SortFilter;

#[ApiResource]
#[QueryParameter(key: 'fields', filter: SparseFieldset::class)]
#[QueryParameter(key: 'sort', filter: SortFilter::class)]
class Book extends Model {}

具体功能实现

1. 排序功能

JSON:API 规范的排序功能非常直观:

  • 升序排序:/books?sort=title
  • 降序排序:/books?sort=-publishedAt
  • 多字段排序:/books?sort=author.lastName,title

在 API Platform Laravel 中,排序功能通过 SortFilter 类实现,配置后即可自动支持这些查询方式。

2. 分页功能

分页功能在 JSON:API 中有多种实现方式:

  • 基于偏移量的分页:/books?page[offset]=0&page[limit]=10
  • 基于页码的分页:/books?page[number]=1&page[size]=10

API Platform Laravel 的 JsonApiProvider 已经内置了对分页的支持,无需额外配置即可使用。

3. 过滤功能

过滤功能是 JSON:API 中最灵活的部分,允许对资源进行精确查询:

  • 简单过滤:/books?filter[title]=API
  • 多条件过滤:/books?filter[author.name]=John&filter[year]=2023

在 API Platform Laravel 中,过滤功能需要针对每个字段单独配置:

#[ApiResource(
    operations: [
        new GetCollection(
            name: 'books',
            parameters: [
                new QueryParameter(
                    key: 'filter[title]',
                    filter: PartialSearchFilter::class,
                    property: 'title'
                ),
                new QueryParameter(
                    key: 'filter[publishedAt]',
                    filter: DateFilter::class
                ),
            ],
        ),
    ],
)]
class Book extends Model {}

高级过滤实现

对于需要更复杂过滤逻辑的场景,可以创建自定义过滤器。例如,实现一个支持多种比较操作符的过滤器:

namespace App\Filters;

use Illuminate\Database\Eloquent\Builder;

class AdvancedFilter
{
    public function __invoke(Builder $query, string $property, $value): void
    {
        if (is_array($value)) {
            foreach ($value as $operator => $val) {
                match ($operator) {
                    'eq' => $query->where($property, '=', $val),
                    'gt' => $query->where($property, '>', $val),
                    'lt' => $query->where($property, '<', $val),
                    'like' => $query->where($property, 'LIKE', "%$val%"),
                    default => null,
                };
            }
        } else {
            $query->where($property, '=', $value);
        }
    }
}

然后在资源配置中使用:

new QueryParameter(
    key: 'filter[price]',
    filter: AdvancedFilter::class,
    property: 'price'
)

这样就可以支持如下的查询方式:

  • /products?filter[price][gt]=100
  • /products?filter[price][lt]=50
  • /products?filter[name][like]=phone

最佳实践建议

  1. 保持一致性:在整个 API 中统一使用 JSON:API 规范的查询参数格式
  2. 文档化:为每个资源的可用过滤字段和操作符提供清晰的文档
  3. 性能考虑:为常用过滤字段添加数据库索引
  4. 安全性:验证所有输入参数,防止 SQL 注入
  5. 适度过滤:不要过度开放过滤能力,根据业务需求合理设计

通过合理配置 API Platform Laravel,我们可以轻松实现符合 JSON:API 规范的完整查询功能,为前端开发者提供一致且强大的 API 查询体验。

登录后查看全文
热门项目推荐
相关项目推荐