sajad torkamani

In a nutshell

API Platform provides a DateFilter class that lets you filter your API resources by date intervals.

The syntax is:

?property[<after|before|strictly_after|strictly_before>]=value

The value can be any date format supported by the DateTime constructor. See this page for more info on support date formats.

The after and before filters will include the value whereas strictly_after and strictly_before will exclude the value.

Example usage

Enable the filter

<?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\DateFilter;

#[ApiResource]
#[ApiFilter(DateFilter::class, properties: ['createdAt'])]
class Offer
{
    // ...
}

Use the filter

GET /offers?createdAt[after]=2018-03-19

This will return all the offers where the createdAt is greater than or equal to 2018-03-19

Filter by exact date

By default, the DateFilter class doesn’t seem to provide a way to filter by an exact date. To filter by an exact date such as 2021-07-12, I set the [after] to that date and the [before] to one day after the target date (2021-07-13 in this case). So something like this:

GET /offers?createdAt[after]=2021-07-12&createdAt[before]=2021-07-13

Handle null values

The DateFilter can be configured to treat null in a number of ways. See the docs for more info.

Sources

Leave a comment

Your email address will not be published. Required fields are marked *