Why is checking for a json mimetype not working in my Request? - laravel

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.

Related

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:
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.

Laravel: Output array of bytes to browser in pdf format

I am getting a response from an external api which contains an array of bytes I'd like to convert to pdf.
Sample response from the api.
So far, I have tried below code in laravel with no success.
$data is received from api.
return response($data)
->withHeaders([
'Content-Type'=> 'application/pdf'
]);
The trick is to set the Content-Disposition header to force a download.
return response($data, 200, [
'Content-type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="api.pdf"',
]);
You could also replace attachment with inline to render the pdf in the browser (most modern browser support this).

Laravel api header request

Route::resource('get-users','api\UserController#get_users');
Route::resource('register','api\UserController#register');
My Api is giving me the response I checked it using POSTMAN but android developer is asking me that what should he sent in header for my API .
I am not getting that how to create a header I am using laravel and I have written functions in controller .
You should go through this part of the documentation: https://laravel.com/docs/5.6/responses#attaching-headers-to-responses
He maybe wants additional header in the response.
Your return value in api\UserController can be extended like this:
return response($content)
->withHeaders([
'Content-Type' => $type,
'X-Header-One' => 'Header Value',
'X-Header-Two' => 'Header Value',
]);

MultiJson::LoadError: 795: unexpected token when trying to parse incoming body request

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 }

Unable to decode request as valid JSON using RUBY

I am making the following API GET request, using ruby 1.9.3 and the httparty gem:
uri= HTTParty.post("www.surveys.com/api/v2/contacts",
:basic_auth => auth,
:headers => { 'ContentType' => 'application/json' },
:body => {
"custom_test" => test,
"name" => firstname,
"email" => emailaddress
}
)
The variables auth,test,firstname, and emailaddress are valid. This is the response I am receiving back from my request:
{
"code": "invalid_json",
"description": "Request sent with Content-Type: application/json but was unable to decode request body as valid json.",
"success": false
}
500
#<Net::HTTPInternalServerError:0x007fe4eb98bde0>
What is wrong with the way I am posting this JSON request?
EDIT: It's probably worth noting that the API allows you to define custom attributes to a contact, hence the "custom_test" attribute in the body.
Since you are receiving an internal server error (500) instead of a not accepted (406), most likely there is coding problem on the server, because an exception that he is not expecting is happening instead of delivery to you a nice error explaining what is wrong (and this would be my first guess).
But let's say it is a problem with the JSON communication. Maybe you have to specify that you are accepting json format?
Try
:headers => { 'ContentType' => 'application/json', 'Accept' => 'application/json' },
Accept header definition from w3:
The Accept request-header field can be used to specify certain media types which are acceptable for the response. Accept headers can be used to indicate that the request is specifically limited to a small set of desired types, as in the case of a request for an in-line image.
And content-type header definition:
The Content-Type entity-header field indicates the media type of the entity-body sent to the recipient or, in the case of the HEAD method, the media type that would have been sent had the request been a GET.
You're sending a regular HTTP query string while saying it's json.
From HTTParty manual: "body: The body of the request. If it‘s a Hash, it is converted into query-string format, otherwise it is sent as-is."
Try:
:body => JSON.generate({
"custom_test" => test,
"name" => firstname,
"email" => emailaddress
})
You need to require 'JSON'

Resources