Reputation: 310
I'm trying to build Symfony API with the bundle, but every request that I sent has empty body.
Controller:
class IndexController extends AbstractFOSRestController
{
/**
* @Rest\Post("/api/test", methods={"POST"})
* @param Request $request
* @return View
*/
public function testError(
Request $request
) : View {
$requestData = $request->request->all(); // problem: requestData is []
return View::create()
->setStatusCode(200)
->setFormat("json")
->setData(["data" => $requestData, "status" => "ok"]);
}
}
I am sending this request from CURL:
curl -d '{"key1":"value1", "key2":"value2"}' -H "Content-Type: application/json" -X POST http://localhost:8000/api/test
I've also tried sending it with Postman. I receive this response:
{"data":[],"status":"ok"}
Here is my fos_rest.yaml file:
fos_rest:
view:
view_response_listener: true
format_listener:
rules:
- { path: ^/api, prefer_extension: true, fallback_format: json, priorities: [ json, html ] }
- { path: ^/, prefer_extension: true, fallback_format: json, priorities: [ html, json ] }
Upvotes: 1
Views: 2145
Reputation: 2904
I think you forgot about proper serializer, which is mostly required. Here is my config, should help you with it:
fos_rest:
serializer:
serialize_null: true
body_listener:
enabled: true
throw_exception_on_unsupported_content_type: true
decoders:
json: fos_rest.decoder.json
format_listener:
rules:
- { path: '^/api', priorities: ['json'], fallback_format: json, prefer_extension: false }
- { path: '^/', priorities: ['html', '*/*'], fallback_format: html, prefer_extension: true }
param_fetcher_listener: force
view:
view_response_listener: 'force'
formats:
json: true
allowed_methods_listener: true
services:
fos_rest.decoder.json:
class: FOS\RestBundle\Decoder\JsonDecoder
public: true
Manual
Symfony: Setting up the bundle, part B
Upvotes: 4
Reputation: 310
Edit: One way to fix it is the accepted answer, the other is the below code
$requestData = json_decode($request->getContent(), true);
return View::create()
->setStatusCode(200)
->setFormat("json")
->setData(["data" => $requestData, "status" => "ok"]);
Upvotes: 0