Hello, trying to create REST API in my MVC project. Correct me if I am wrong.
First of all declared roustes:
$router->addGet( "/api/products", "api::products" );
$router->addGet( "/api/products/{ean:[0-9]+}", "api::productByEAN" );
$router->addPost( "/api/products", "api::productCreate" );
Then in my ApiController.php created basic functions:
<?php
class ApiController extends ControllerBase {
public function productsAction() { return "all products"; } public function productByEANAction() { $ean = $this->dispatcher->getParam("ean"); return $ean; // just check if returning correct value for now } public function productCreateAction() { $postData = $this->request->getJsonRawBody(); $rawPostData = $this->request->getRawBody(); // testing purpose $post = $this->request->getPost(); // testing purpose $data = file_get_contents("php://input"); // testing purpose $data = json_decode($data, TRUE); // testing purpose return var_dump($postData) . " " . var_dump($rawPostData) . " " . var_dump($post) . " " . var_dump($data); }
}
There is my problem. Now when I am trying to get posted JSON data getJsonRawBody() returns null. Trying with curl:
curl -d '{"key1":"value1", "key2":"value2"}' -H "Content-Type: application/json" -X POST https://localhost/po-web/api/products
Result:
G:\xampp\htdocs\po-web>curl -d '{"key1":"value1", "key2":"value2"}' -H "Content-Type: application/json" -X POST https://localhost/po-web/api/products curl: (3) [globbing] unmatched close brace/bracket at pos 12 NULL string(14) "'{key1:value1," array(0) { } NULL
Error causes space between value1 and key2. Why?
With deleted space getJsonRawBody() still dont working but dont raise error.
curl -d '{"key1":"value1","key2":"value2"}' -H "Content-Type: application/json" -X POST https://localhost/po-web/api/products
Result:
G:\xampp\htdocs\po-web>curl -d '{"key1":"value1","key2":"value2"}' -H "Content-Type: application/json" -X POST https://localhost/po-web/api/products NULL string(27) "'{key1:value1,key2:value2}'" array(0) { } NULL
Thank you for any help.