我想为我的一个端点启用PUT
方法的上装。因此,无论记录存在于何处,都会对其进行更新;如果记录不存在,则会对其进行创建。我在Symfony 4.2中使用Api-Platform。
api平台的默认行为似乎根本不支持它-当我尝试使用获取PUT
之前未创建的数据发出404 Response
请求时。
我确实遵循了官方手册recommended way of using custom operations(下面的实体代码),但在获得定制服务之前,我仍然得到404 Response
。
是否有可能使其正常工作?批注映射是正确的,请在发布末尾登录。
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use ApiPlatform\Core\Annotation\ApiResource;
/**
* @ORM\Entity()
* @ApiResource(
* collectionOperations={},
* itemOperations={
* "get",
* "special"={
* "method"="PUT",
* "path"="/dummys/{id}",
* "controller"=DummysController::class
* }
* }
* )
*/
class Dummy
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
*/
private $name;
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
}
请求+日志:
curl -X PUT "http://localhost/api/v1/dummys/non-existing-id" -H "accept: application/ld+json" -H "Content-Type: application/json" -d "{ \"name\": \"string\"}"
request.INFO: Matched route "api_dummys_special_item". {"route":"api_dummys_special_item","route_parameters":{"_route":"api_dummys_special_item","_controller":"App\\Controller\\DummyController","_format":null,"_api_resource_class":"App\\Entity\\Dummy","_api_item_operation_name":"special","id":"non-existing-id"},"request_uri":"http://localhost/api/v1/dummys/non-existing-id","method":"PUT"} []"
doctrine.DEBUG: SELECT (...) WHERE p0_.id = ? ["non-existing-id"] []"
request.ERROR: Uncaught PHP Exception Symfony\Component\HttpKernel\Exception\NotFoundHttpException: "Not Found" at /app/vendor/api-platform/core/src/EventListener/ReadListener.php line 108 {"exception":"[object] (Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException(code: 0): Not Found at /app/vendor/api-platform/core/src/EventListener/ReadListener.php:108)"} []"
答案 0 :(得分:1)
您是否尝试过文档中有关如何bypass the automatic retrieval的部分?
基本上添加选项_api_receive
:
/**
* @ORM\Entity()
* @ApiResource(
* collectionOperations={},
* itemOperations={
* "get",
* "special"={
* "method"="PUT",
* "path"="/dummys/{id}",
* "controller"=DummysController::class,
* "defaults"={"_api_receive"=false} <---- add this
* }
* }
* )
*/