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:
Form data Request:
Why its not working in case of JSON, content-type is application/json, Accept:*/*???
Comments are not permitted in JSON.
There's a bug in the field Body -> raw -> json
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:
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
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.
Related
I have a Laravel API and I make a custom Request to validate the values. I'm testing my routes via Postman and I added a JSON file to my settings field. But when I try to validate the mimetype in my custom request an error gets thrown. When I remove |mimetypes:application/json the route returns a response successfully. Why is this happening?
public function rules()
{
return [
'name' => 'required|string|min:2|max:32|unique:game_templates',
'path' => 'required|string|url|unique:game_templates',
'settings' => 'required|file|mimetypes:application/json',
'orientation' => Rule::in(GameTemplate::$orientations),
];
}
The JSON content
{
"name":"test"
}
Are you sure you are actually uploading a file with the application/json mimetype? A .json extension doesn't automatically mean it's application/json. Also note the following from the documentation:
To determine the MIME type of the uploaded file, the file's contents will be read and the framework will attempt to guess the MIME type, which may be different from the client provided MIME type.
I use this method:
public function store(CreateEvent $request)
{
dd($request->json()->all());
}
My requests is:
{"name":"etegjgjghjghj","date":"2019-03-08"}
Headers:
Accept: application/json, text/plain, */*
Content-Type: application/json
Origin: http://localhost:4200
As response I get blank page in Chrome network without response data.
I tried this:
public function store(CreateEvent $request){ dd('test'); }
try this:
public function store(CreateEvent $request)
{
return response()->json($request->all());
}
If the request has header 'Content-Type: application/json' and it's a valid JSON, then laravel will convert it automatically. You don’t need to do any extra job.
But you have to make sure the JSON is correct. Because JSON must contain double quoted strings not single (if has any)
Next thing, your form validation probably shooting 422 request which by default redirects back to previous page. you can try dd in the form request class
I want to consume my own API (with authentification) for my website which is on the same domain. For instance, if the user of the website wants to see the list of the posts:
1. He goes to mywebsite/posts, thus making a GET /mywebsite/posts request.
2. The web app dispatches the request and calls the listPosts() function of the WebsiteController.
3. The listPosts() function creates a new request to the API like that:
$token = 'd0aE73j...';
$request = Request::create('/api/posts', 'GET', [], [], [], [
'Authorization' => 'Bearer '.$token, //The header for authentification
'Accept' => 'application/json', //The header supposed to prevent the error below
], []);
$response = Route::dispatch($request);
4. The JSON result of the request is passed and displayed in the view of the list of posts:
return view('mywebsite.listposts')->with('listPosts',$response);
The problem I have is at 3., the request returns an error:
InvalidArgumentException: Route [login] not defined. in file C:[...]\vendor\laravel\framework\src\Illuminate\Routing\UrlGenerator.php on line 370
What I want to know is:
1) How to make a proper HTTP request with headers to my own API,
2) How to return a JSON instead of this error when the Accept: application/json is not present.
Thank you for your help.
I have the following code in my controller:
public function upload(Request $request)
{
$files = $request->file('uploads');
if(!empty($files)) {
foreach($files as $file) {
Storage::put($file-getClientOriginalName(),file_get_contents($file));
}
}
Which is called via an api.php in routes:
Route::post('/upload', [ 'uses' => 'UploadController#upload' ]);
I am using postman to test my application.
Header:
Body:
Raw:
POST /scotic/public/api/upload HTTP/1.1 Host: 127.0.0.1:80
Content-Type: multipart/form-data;
boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW Cache-Control: no-cache
Postman-Token: 0caf7349-5c91-e5f1-766f-72a3f1e33900
------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="uploads[]"; filename="banana.png" Content-Type:
image/png png data goes here..
------WebKitFormBoundary7MA4YWxkTrZu0gW--
The $files is empty upon uploading the file. What am i doing wrong?
After a bit of digging, I got my uploader working without postman, I noticed that the '--boundary' was missing from the Content-Type in postman. The LHS works, RHS(postman) does not work.
Any ideas?
The issue was that I was explicitly specifying the Content-Type in postman.
According to one of the answers from this post:
There is no need to add a content-type header manually. You are overriding the value set by Postman. Just select form-data in POST request and send your request to see if it works.
I'm losing my sanity trying to parse an incoming request on a Sinatra app.
This is my spec
payload = File.read("./spec/support/fixtures/payload.json")
post "/api/v1/verify_payload", { :payload => payload }
last_response.body.must_equal payload
where is simply spec/support/fixtures/payload.json
{"ref":"refs/heads/master"}
My route looks like
post '/verify_payload' do
params = MultiJson.load(request.body.read, symbolize_keys: true)
params[:payload]
end
And running the spec I get the following error:
MultiJson::LoadError: 795: unexpected token at 'payload=%7B%22ref%22%3A%22refs%2Fheads%2Fmaster%22%7D'
I have tried to parse the body request in different ways without luck.
How can I make the request valid JSON?
THANKS
If you want to send a JSON-encoded POST body, you have to set the Content-Type header to application/json. With Rack::Test, you should be able to do this:
post "/api/v1/verify_payload", payload, 'CONTENT_TYPE' => 'application/json'
Alternatively:
header 'Content-Type' => 'application/json'
post '/api/v1/verify_payload'
More info here: http://www.sinatrarb.com/testing.html
The problem it is that you are passing a ruby hash, that is not well formated, you should pass a json object.
Something like this, should work:
post "/api/v1/verify_payload", { :payload => payload.to_json }