I am creating a REST API using CakePHP 5. I have a POST function that should receive the data from postman and input it to the database. The problem is I am not receiving the data in the request. The GET request is working well so this is definitely not a database issue. The received data is being shown as an empty array []
with 200 as a response code. Thank you for your time.
routes.php
$routes->scope('/api', function (RouteBuilder $builder): void {
$builder->connect('/product/insert', ['controller' => 'Product', 'action' => 'insertProduct'])->setMethods(['POST']);
});
ProductController.php
public function insertProduct()
{
$product = $this -> Product -> newEmptyEntity();
$product = $this -> Product -> patchEntity($product, $this -> request -> getData());
$this -> Product -> save($product);
}
Other things I have tried from the framework’s documentation:
$product_name = $this -> request -> getData('product_name');
$product = $this -> Product -> newEntity([
'name' => $product_name,
]);
$content = json_encode(['method' => __METHOD__, 'class' => get_called_class()]);
$data = $this->request->getParsedBody();
$product = $this -> Product -> newEntity($this->request->getData());
debug($this->request);
I also have Table and Entity classes:
ProductTable.php
namespace AppModelTable;
use CakeORMTable;
class ProductTable extends Table
{
public function initialize(array $config): void
{
$this -> setTable('product');
parent::initialize($config);
}
}
Product.php
namespace AppModelEntity;
use CakeORMEntity;
class Product extends Entity
{
}
Postman Snippet
2
Answers
The answer by wappy is the correct answer
You need to send the request with header: Content-Type: application/x-www-form-urlencoded. In Postman, change radio selection from 'form-data' to 'x-www-form-url-encoded' and debug the request: debug($this->request->getData());
Change radio selection from ‘form-data’ to ‘x-www-form-url-encoded’ in Postman and you should have data in $_POST: