I noticed that Laravel has a neat method Request::wantsJson
- I assume when I make the request I can pass information to request a JSON response, but how do I do this, and what criteria does Laravel use to detect whether a request asks for JSON ?
I noticed that Laravel has a neat method Request::wantsJson
- I assume when I make the request I can pass information to request a JSON response, but how do I do this, and what criteria does Laravel use to detect whether a request asks for JSON ?
It uses the Accept
header sent by the client to determine if it wants a JSON response.
Let's look at the code :
public function wantsJson() {
$acceptable = $this->getAcceptableContentTypes();
return isset($acceptable[0]) && $acceptable[0] == 'application/json';
}
So if the client sends a request with the first acceptable content type to application/json
then the method will return true.
As for how to request JSON, you should set the Accept
header accordingly, it depends on what library you use to query your route, here are some examples with libraries I know :
Guzzle (PHP):
GuzzleHttpget("http://laravel/route", ["headers" => ["Accept" => "application/json"]]);
cURL (PHP) :
$curl = curl_init();
curl_setopt_array($curl, [CURLOPT_URL => "http://laravel/route", CURLOPT_HTTPHEADER => ["Accept" => "application/json"], CURLOPT_RETURNTRANSFER => true]);
curl_exec($curl);
Requests (Python) :
requests.get("http://laravel/route", headers={"Accept":"application/json"})