0
votes

Laravel API is not accepting JSON request. If I request as form-data it works but if I post JSON object in postman body then it does not receive the request data.

Route:

$router->group(['prefix' => 'imp'], function () use ($router) {
    $router->group(['prefix' => 'lead'], function () use ($router) {
        $router->post('/jardy', 'FeedController@jardy');
    });
});

Controller:

 public function jardy(Request $request)
    {

        $this->validate($request, [
            'api_key' => 'required',
        ]);
        $api_key = $request->input('api_key');
        return $api_key;
}

JSON Request:

Postman request using JSON

Form data Request:

Postman request using Form data

Why its not working in case of JSON, content-type is application/json, Accept:*/*???

2
does $request->validate([ 'api_key' => 'required' ]) work?apokryfos
yes its working, when i use form-data it works. its like $this->validate($request, [ 'api_key' => 'required', ]);. You have nissed $request.Imdad Ali
Can you try ->validate($request->all() instead of ->validate($requestDilip Hirapara
``` validate ``` method expects Request object. It shows error when i modify like you are suggesting. @Dilip HiraparaImdad Ali
Notice I am using the validate method on $request not on $thisapokryfos

2 Answers

2
votes

Comments are not permitted in JSON. There's a bug in the field Body -> raw -> json

1
votes

You have to add the header

Accept: application/json

Then laravel parses your RAW json as input vars and they can be accesed with ->input()

see: enter image description here

using / which is the postman default, will not work.. If you dont want to relay on the header, you could also do $request->json() but i guess, you just want to pass the header.

See the source that handles this: https://github.com/laravel/framework/blob/7.x/src/Illuminate/Http/Concerns/InteractsWithContentTypes.php#L52

and https://github.com/laravel/framework/blob/7.x/src/Illuminate/Http/Concerns/InteractsWithContentTypes.php#L32