Reputation: 25
I'm working on a restful API solution in Laravel. My problem is that I cannot make my store function accept JSON. In my store function I have the following code (based on this tutorial http://code.tutsplus.com/tutorials/laravel-4-a-start-at-a-restful-api-updated--net-29785):
public function store()
{
$url = new Url;
$url->url = Request::get('url');
$url->description = Request::get('description');
$url->save();
return Response::json(array(
'error' => false,
'message' => 'test',
'urls' => $url->toArray()),
200
);
}
When I send my data like this:
curl -d "url=test&description=testing" localhost/api/v1/url
it works as expected and the record is inserted into my database.
However, when I try to post some JSON like this
curl -d '{"url":"test","description":"test"}' localhost/api/v1/url
I can't even return the data by using Request::get('url'). I've read here on SO that Input::all() or Input::json()->all() would work, but I still can't return the data i'm posting. Any ideas how I can access url and description when it is posted as JSON?
Upvotes: 0
Views: 4040
Reputation: 87719
You're not using curl correctly to post a json, try this:
curl -X POST -H "Content-Type: application/json" -d '{"url":"test","description":"test"}' localhost/api/v1/url
If you are using a Windows client, you can use Postman (http://www.getpostman.com/), a Chrome plugin.
Configure it to:
1) POST
2) raw (and paste your json in the box)
3) Header: Content-Type Value: application/json
And to do your tests you can use a simple router like this:
Route::any('test', function() {
Log::info(Input::all());
});
And execute
php artisan tail
To see what happens when you post.
Upvotes: 4