Make WordPress Core

Opened 2 years ago

Last modified 2 years ago

#56368 new enhancement

Unable to use enum with array data type - REST API

Reported by: picocodes's profile picocodes Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version:
Component: REST API Keywords:
Focuses: rest-api Cc:

Description

I would like to be able to specify enums when creating a REST schema property that accepts an array of values.

For example:

<?PHP
   $query_schema['orderby'] = array(
        'description'       => __( 'Sort collection by object attribute.' ),
         'type'             => array( 'string', 'array' ),
         'default'          => 'id',
         'items'            => array(
              'type' => 'string',
         ),
         'enum'              => array( 'id', 'title', 'date', 'include' ),
         'validate_callback' => 'rest_validate_request_arg',
   );           

Change History (3)

#1 @anna.bansaghi
2 years ago

Hi @picocodes, thank you for your report!

I have tested your schema with this validator https://jsonschemalint.com/#!/version/draft-04/markup/json, and not accepting array values is the correct behavior.

What do you think, can you use the schema below instead? It will accept both string values like 'id', and array values like ['id', 'title']:

<?php
   $query_schema['orderby'] = array(
    'description'       => __( 'Sort collection by object attribute.' ),
    'default'           => 'id',
    'oneOf'             => array(
        array(
            'type' => 'string',
            'enum' => array(
                'id',
                'title',
                'date',
                'include'
            )
        ),
        array(
            'type'  => 'array',
            'items' => array(
                'type' => 'string',
                'enum' => array(
                    'id',
                    'title',
                    'date',
                    'include'
                )
            )
        )
    ),
    'validate_callback' => 'rest_validate_request_arg',
);
Last edited 2 years ago by anna.bansaghi (previous) (diff)

#2 @anna.bansaghi
2 years ago

  • Keywords reporter-feedback added

#3 @anna.bansaghi
2 years ago

  • Keywords reporter-feedback removed

I have just noticed another ticket which was reporting issues with the schema I have suggested: #54740
I am sorry giving bad advice!

Last edited 2 years ago by anna.bansaghi (previous) (diff)
Note: See TracTickets for help on using tickets.