How to get JSON from request Laravel? - laravel

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

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.

response with appropriate mime type requested with accept

Say I have a route:
Route::get('list',...);
If I call that route with Accept: text/html it should return a view with all the blade hoopla.
If I call that route with Accept: application/json it should return json, Accept: application/xml it will return xml.
And so on...
How do I realise that with Laravel 5.1?
You can handle Accept header using these methods of the Request class:
bool accepts(string|array $contentTypes)
If you just care about Json and HTML there is
bool acceptsJson() / bool wantsJson()
bool acceptsHtml()

Laravel file upload API using Postman

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.

Always empty response with $.getJSON

I have a simple web service that outputs a JSON object to a client.
If accessed with a plain browser it outputs the JSON string. However when accessed with $.getJSON it always return a empty response although there is a response header:
Content-Type application/json; charset=utf-8
Content-Length 122
Connection keep-alive
The code for the call is like this:
$.getJSON('http://192.168.0.1/api/v1/search', { query : $('#searchfield').val() },
function(data){
$.log("Response: %s", data.some_field);
}
);
Also the callback function is not invoked.
Any ideas?

REST method's won't PUT or POST to the server

I'm trying to get some REST methods working in my Spring app but seem to be running into little success. I'm obviously missing something but I can't tell for the life of me what it would be. Here is my controller:
#Controller
public class IndexController {
static Logger log = Logger.getLogger(IndexController.class);
#Autowired
private ProvisionService provisionService;
#RequestMapping(value="/home/data", method=RequestMethod.GET,
headers="Accept=application/json")
public #ResponseBody List<Provision> getData() {
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String username = null;
if(principal instanceof UserDetails)
username = ((UserDetails)principal).getUsername();
return provisionService.getAllByUser(username);
}
//JSON put request - doesn't work currently
#RequestMapping(value="/home/data", method=RequestMethod.PUT,
headers="Content-Type=application/json")
#ResponseStatus(HttpStatus.NO_CONTENT)
public void updateProvisions(#RequestBody List<Provision> provisions) {
log.info("Provisions: " + provisions.toString());
}
#RequestMapping(value={"/","/home"}, method=RequestMethod.GET)
public void showIndex() {}
}
Here is the main part of JSP that utilizes it:
<sf:form id="homeForm" method="put" action="${homeData_url}"></sf:form>
The form is submitted through Javascript when the user clicks on a button. Anyway, things work fine for the GET. I get Json returned with my List of objects, no problems. I then display that using Dojo and so far so good. However, when I try to return the Json with this form I'm getting a 405 - Request method 'POST' not supported error. As you can see I've got the method handler in my Controller so I'm really not sure what I'm doing wrong. I've taken those handler's out of the Spring in Action 3 book and it also resembles what some Spring docs and stuff say to do, but obviously I'm missing a key component. Anyone have any thoughts?
I do have the HiddenHttpMethodFilter mapped in my web.xml which is why I'm using the Spring form tag.
Anyway, any thoughts or help are appreciated. Thank you.
------------------UPDATE------------------
Here are the headers after I click on the button and get the 405 error, if it helps:
http://localhost:8080/NFI/home
POST /NFI/home HTTP/1.1
Host: localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:7.0.1) Gecko/20100101 Firefox/7.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
DNT: 1
Connection: keep-alive
Referer: http://localhost:8080/NFI/home
Cookie: JSESSIONID=584AC21ADE4F214904B9E7E2370363EF
Content-Type: application/x-www-form-urlencoded
Content-Length: 11
HTTP/1.1 405 Method Not Allowed
Server: Apache-Coyote/1.1
Allow: GET, PUT
Content-Type: text/html;charset=utf-8
Content-Length: 1085
Date: Fri, 21 Oct 2011 15:39:26 GMT
Submitting a Form is done using POST. You get a "POST" not supported error.
Above, I see you are using a RequestMethod.PUT in your source code. There's no mention of POST at all.
Add you need to add a parameter _method with value PUT to your request. Not to the json content!
So in the first step I would change requested URL to /home/data?_method=PUT.
If this work you can search for an way how to add the _method parameter to the request content without disturbing the Json data.
You updated your question with the headers, could you also put the entire request out there (actual dumped values) to see the _method parameter(s) being sent?
Also, while I guess the headers=""-rules are valid they shouldn't be needed. You have a json converter bean that will do marshall and unmarshall based on content-type and accept headers, if no valid converter is found Spring will return an error.
The only reason to include it in the #RequestMapping would be if you had a method that actually did something else if you called it with xml instead of json and that sounds like a bad design.
Remove those header-rules and try again, make it as simple as possible and gradually add logic.

Resources