Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to organize parsing and validation of REST API parameters?

Tags:

rest

php

api

I have a rest api that has many parameters via the query string. I am wondering if someone knows of a design pattern or has a nice way of organizing all the parameters (Objects, functions, array, json). Right now I am parsing and validating all my parameters in the same function, very ugly code.

Ideally I would like some way to handle the parameters similar to a database ORM or even a config file/array/json. However, I have tried to come up with a solution to this without any luck.

Any insight would be appreciated!

Example of my thoughts:

<?php
...

$parameters = [
    // ?fields=id,name
    'fields' => [
        'default'  => ['id', 'name'],
        'valid'    => ['id', 'name', 'date],
        'type'     => 'csv', // list of values (id & name)
        'required' => ['id'],
        'replace'  => ['title' => 'name'], // if the database & api names don't match
        'relation' => null, // related database table
    ],
    // ?list=true
    'list' => [
        'default'    => ['false'],
        'valid'      => ['true', 'false'],
        'type'       => 'boolean' // single value (true or false)
        'required'   => [],
        'replace'    => [], // if the database & api names don't match
        'relation'   => 'category', // related database table
    ],
    ....

];
like image 468
rand0mb1ts Avatar asked Nov 02 '22 15:11

rand0mb1ts


1 Answers

Seems to me like you are looking for a validation library. My favorite is Symfony's: https://github.com/symfony/validator. I know Zend Framework 2 also has a validation component. I haven't used it personally, but I expect that to be very good too.

Example from the symfony/validator readme:

<?php

use Symfony\Component\Validator\Validation;
use Symfony\Component\Validator\Constraints as Assert;

$validator = Validation::createValidator();

$constraint = new Assert\Collection(array(
    'name' => new Assert\Collection(array(
        'first_name' => new Assert\Length(array('min' => 101)),
        'last_name'  => new Assert\Length(array('min' => 1)),
    )),
    'email'    => new Assert\Email(),
    'simple'   => new Assert\Length(array('min' => 102)),
    'gender'   => new Assert\Choice(array(3, 4)),
    'file'     => new Assert\File(),
    'password' => new Assert\Length(array('min' => 60)),
));

$input would be $_GET or something obtained with parse_str etc. It is also possible to define the validation rules in some other format, such as YAML.

like image 169
Peter Avatar answered Nov 15 '22 04:11

Peter