我需要使用symfony2创建一个REST api。没有UI,没有形式只是一个REST API。
我尝试创建一个简单的CRUD系统但是我对更新有疑问。
那么,
config.yml
fos_rest:
param_fetcher_listener: force
routing_loader:
default_format: json # All responses should be JSON formated
include_format: false
exception:
enabled: true
FeatureController:
<?php
namespace AppBundle\Controller;
use AppBundle\Entity\Feature;
use FOS\RestBundle\Controller\Annotations;
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Request\ParamFetcher;
use Guzzle\Http\Message\Request;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use FOS\RestBundle\Controller\Annotations\RouteResource;
use FOS\RestBundle\Controller\Annotations\RequestParam;
use FOS\RestBundle\Controller\Annotations\QueryParam;
use FOS\RestBundle\View\View;
/**
* @RouteResource("Feature", pluralize=false)
*/
class FeatureController extends FOSRestController
{
/**
* @param ParamFetcher $params
* @RequestParam(name="type", requirements="[0-9]", default="0", description="type")
* @RequestParam(name="name", requirements="[a-z]+", description="name")
*
* @return array
*/
public function postAction(ParamFetcher $params){
$feature = new Feature();
$feature
->setType($params->get('type'))
->setName($params->get('name'));
$em = $this->getDoctrine()->getManager();
$em->persist($feature);
$em->flush();
$view = View::create();
$view->setStatusCode(201);
return $this->handleView($view);
}
/**
* @param $id
* @param ParamFetcher $paramFetcher
* @RequestParam(name="type", requirements="[0-9]", default="0", description="type")
* @RequestParam(name="name", requirements="[a-z]+", description="name")
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function patchAction($id, ParamFetcher $paramFetcher){
$view = View::create();
$view
->setStatusCode(200)
->setData([$id, 'params' => $paramFetcher->all()]);
return $this->handleView($view);
}
/**
* @param $id
* @param ParamFetcher $paramFetcher
* @QueryParam(name="page", requirements="\d+", description="Page of the overview.")
*
* @return Response
*/
public function getAction($id, ParamFetcher $paramFetcher){
$view = View::create();
$view->setData(['id' => $id, 'params' => $paramFetcher->all()])->setStatusCode(200);
return $this->handleView($view);
}
}
当我使用此url / feature / 5?page = 55的getAction时,响应是正确的
{
"id": "5",
"params": {
"page": "55"
}
}
$ id,ParamFetcher $ paramFetcher工作正常。
当我使用postAction with / feature和body
时{
"type" : 2,
"name" : "aze"
}
它也可以。
但是当我尝试将patchAction与/ feature / 5和body一起使用时 { &#34;类型&#34; :5, &#34;名称&#34; :&#34; newName&#34; }
回复是:
{
"code": 400,
"message": "Parameter type value '' violated a constraint (This value should not be null.)"
}
有你的想法吗?
PS:这是我第一次使用FOSRestBundle,如果你有一些最佳实践,请不要犹豫。