sajad torkamani

In a nutshell

API Platform provides the OrderFilter class to let you order your collections by specific properties.

The syntax is:

?order[property]=<asc|desc>

Enable ordering on specific properties

<?php
// api/src/Entity/Offer.php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiFilter;
use ApiPlatform\Core\Annotation\ApiResource;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\OrderFilter;

#[ApiResource]
#[ApiFilter(OrderFilter::class, properties: ['id', 'name'])]
class Offer
{
    // ...
}

Now, you can order the /offers endpoint with a request like:

/offers?order[name]=desc&order[id]=asc

Filters aren’t applied unless you pass the order query param or you specify a default sort order (via the order attribute to the ApiResource annotation.

Filter on nested properties

Use the dot syntax to configure the ordering on a nested property:

<?php
// api/src/Entity/Offer.php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiFilter;
use ApiPlatform\Core\Annotation\ApiResource;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\OrderFilter;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\SearchFilter;

#[ApiResource]
#[ApiFilter(OrderFilter::class, properties: ['product.releaseDate'])]
class Offer
{
    // ...
}

Now, you can do something like:

http://localhost:8000/api/offers?order[product.releaseDate]=desc

Configure custom query param name

By default, you use the order query param, but you can change this:

# api/config/packages/api_platform.yaml
api_platform:
    collection:
        order_parameter_name: '_order' # the URL query parameter to use is now "_order"

Sources