Imdad Ali
Imdad Ali

Reputation: 737

Laravel API not accepting JSON request from Postman

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:*/*???

Upvotes: 4

Views: 8154

Answers (4)

Carver
Carver

Reputation: 109

I think its important to note that invalid json might be the problem here. In my case I was using postman variables and had to enclose them in double quotes

earlier I did {"client_id": {{client_id}}} and so when I changed to {"client_id" : "{{client_id}}"} it worked for me. Hope this helps

Upvotes: 0

EugeneGpil
EugeneGpil

Reputation: 101

In my case it was lack of Content-Length header.

Value should be a number of characters of request body.

Content-Type: application/json also should be present.

Upvotes: 2

gs-design
gs-design

Reputation: 106

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

Upvotes: 9

Danny Ebbers
Danny Ebbers

Reputation: 919

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

Upvotes: 4

Related Questions