在Silex RESTful API

时间:2016-05-20 12:25:51

标签: symfony silex

我正在使用Silex创建RESTful API。测试我正在使用Chrome的“简单REST客户端”插件。

在插件中,我将网址设置为:http://localhost/api-test/web/v1/clients 我将“方法”设置为:POST 我把“标题”留空了 我将“数据”设置为:name = whatever

在我的“clients.php”页面中,我有:

require_once __DIR__.'/../../vendor/autoload.php';
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

$app = new Silex\Application();

$app->post('/clients', function (Request $request) use ($app) {
  return new Response('Created client with name: ' . $request->request->get('name'), 201);
}

在插件中,输出显示:“Status:201”(正确),一堆标题和“Data:Created client with name:”(它应该说“Data:Created client with name:whatever”< / p>

我做错了什么?我也尝试过:$ request-&gt; get('name')

谢谢。

1 个答案:

答案 0 :(得分:3)

需要三个步骤来解决:

1)&#34;简单休息客户&#34;设置&#34; Headers&#34;到:

Content-Type: application/json

2)更改&#34;数据&#34;到:

{ "name": "whatever" }

3)在Silex中添加代码以将输入转换为JSON,如http://silex.sensiolabs.org/doc/cookbook/json_request_body.html中所述:

$app->before(function (Request $request) {
    if (strpos($request->headers->get('Content-Type'), 'application/json') === 0) {
        $data = json_decode($request->getContent(), true);
        $request->request->replace(is_array($data) ? $data : array());
    }
});

然后我可以通过以下方式访问PHP代码中的数据:

$request->request->get('name')

感谢@xabbuh的帮助,这让我得到了答案。

相关问题