dingo / api

A RESTful API package for the Laravel and Lumen frameworks.
BSD 3-Clause "New" or "Revised" License
9.33k stars 1.25k forks source link

How do I set the partial route api.strict option? #1622

Open shankesgk2 opened 5 years ago

shankesgk2 commented 5 years ago
Q A
Bug? no
New Feature? yes
Framework Laravel
Framework version 5.7.18
Package version 2.0.0-alpha2
PHP version 7.2.15

Actual Behaviour

set .ENV API_STRICT=true and request header Accept:application/vnd.xxx.v1+json it's work. but third service request no header Accept:application/vnd.xxx.v1+json and I can't ask them to correcting something. I tried set config(['api.strict' => false]) in loaded middleware, not work.

Expected Behaviour

Accept header could not be properly parsed because of a strict matching process.

Steps to Reproduce

Possible Solutions

$api->get()->apiStrict(false);?

specialtactics commented 5 years ago

Hi @shankesgk2

What happens in Dingo is that the strict option is evaluated and passed to the relevant thing (Http validation) on the bootstrap/register of the service provider for dingo. That means it will happen before any middleware is even executed.

The relevant thing which actually uses this config option is bound to the app container in a singleton pattern in Dingo\Api\Http\Validation\Accept

What you could do in a middleware is potentially get that class using some code like this:

$accept = app('Dingo\Api\Http\Validation\Accept')

And then you could turn the strict option off. Now at the moment it's actually not possible to change the strict option, and I am not sure what repercussions it would have if it were changable. But you could try it yourself, by adding a method like this in that class (\Dingo\Api\Http\Validation\Accept).

    public function setStrict($strict)
    {
        $this->strict = $strict;
    }

So after you add that code in that vendor file, you could do this in your custom middleware:

$accept = app('Dingo\Api\Http\Validation\Accept')
$accept->setStrict(false);

And then you could add this middleware on any route you like, and if you want add some conditions in the middleware, to denote under what circumstances to disable strictness.

If you want to try this option and then give feedback on whether it works for you, and then if it does with no issues, I'd be happy to add that setStrict method.