我正在尝试关注如何使用Symfony2设置一个好的REST API的Will Durand教程.但是,当我收到此错误时,我在一开始就失败了:
The controller must return a response (Array(welcome => Welcome to my API) given).
Run Code Online (Sandbox Code Playgroud)
我的基本配置基本必须是错误的.我已经尝试了不同的fos_rest配置设置,但配置参考并没有提供非常有用,因为我真的不明白单个设置的作用.
我的设置:
//config.yml
sensio_framework_extra:
view:
annotations: true
fos_rest: ~
Run Code Online (Sandbox Code Playgroud)
//Controller
<?php
namespace Acme\Bundle\ApiBundle\Controller;
use FOS\RestBundle\Controller\Annotations as Rest;
class DefaultController
{
/**
* @Rest\View
*/
public function indexAction()
{
return array(
'welcome' => 'Welcome to my API'
);
}
}
Run Code Online (Sandbox Code Playgroud)
我的API应该基于accept标头返回XML或者JSON.永远不会有html输出.
我正在使用带有fos-restbundle的Symfony2开发一个应用程序.我想创建一些API路由以及一些常规路由(只有一个用于AngularJS前端).这是我的fos_rest配置(以及来自sensio的一些配置行):
sensio_framework_extra:
view: { annotations: false }
router: { annotations: true }
request: { converters: true }
fos_rest:
routing_loader:
default_format: json
include_format: true
param_fetcher_listener: force
body_listener: true
allowed_methods_listener: true
view:
view_response_listener: 'force'
formats:
json: true
xml: true
format_listener:
rules:
- { path: '^/api', priorities: ['json', 'xml'], fallback_format: json, prefer_extension: true }
access_denied_listener:
json: true
如您所见,我启用了view_response_listener并禁用了注释.我找不到为索引操作定义"常规"(非REST)路由(和视图)的方法(AngularJS的必要).继续收到错误:
ERROR - Uncaught PHP Exception Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException: "No matching accepted Response format could be determined" at C:\wamp\www\CRMProject\vendor\friendsofsymfony\rest-bundle\EventListener\FormatListener.php line 69
Run Code Online (Sandbox Code Playgroud)
我很感激任何帮助.
在文档中说我们可以在查询参数上应用复杂约束,如:
@QueryParam(
array=true,
name="filters",
requirements=@MyComplexConstraint,
description="List of complex filters"
)
Run Code Online (Sandbox Code Playgroud)
摘自https://github.com/FriendsOfSymfony/FOSRestBundle/blob/master/Resources/doc/3-listener-support.md
但是当我尝试在我的项目中使用它时:
@Annotations\QueryParam(
name="departurePoint",
array=true,
strict=true,
requirements=@DeparturePoint,
nullable=false,
description="The destination from where to start the journey"
)
Run Code Online (Sandbox Code Playgroud)
正确使用DeparturePoint(作为symfony约束实现)时,会抛出一个错误,指出requirements参数只能是一个字符串.
是否可以为queryParam使用自定义验证器?
我正在努力解决与FOSRestBundle相关的问题(版本0.13.*)
我有一些REST API会抛出一些异常,我猜不出异常.但是,尽管我做了特定的配置,允许在响应中格式化异常消息,即使在生产中也是如此(遵循我在此处找到的文档:https://github.com/FriendsOfSymfony/FOSRestBundle/blob/master/Resources/doc/4 -exception-controller-support.md),JSON响应绝对是空的......
示例如下:
http://host/app_dev.php/api/postcode/search?postcode=
Run Code Online (Sandbox Code Playgroud)
结果是:
HTTP 400: {"status":"error","status_code":400,"status_text":"Bad Request","current_content":"","message":"You must provide a postcode"}
Run Code Online (Sandbox Code Playgroud)
但
http://host/api/postcode/search?postcode=
Run Code Online (Sandbox Code Playgroud)
结果是:
HTTP 400: []
Run Code Online (Sandbox Code Playgroud)
我的API控制器如下所示:
/**
* Search post codes
*
* @param Request $request Request
* @param Promotion $promotion Promotion
*
* @Rest\View()
*
* @throws BadRequestHttpException
* @return array
*/
public function searchAction(Request $request, Promotion $promotion)
{
// Get post code
$postCode = $request->query->get('postcode');
if (!$postCode) {
throw new BadRequestHttpException('You must provide a postcode');
}
// SOME …Run Code Online (Sandbox Code Playgroud) 我正在关注本教程http://welcometothebundle.com/symfony2-rest-api-the-best-way-part-3/然后我添加了一个新实体 Author。
使用 GET、POST 和 DELETE 一切都按预期进行,但是在使用 PUT 或 PATCH 时,我得到以下结果:
[{"message":"An exception occurred while executing 'INSERT INTO Author
(id, name, password) VALUES (?, ?, ?)' with params [16, null, null]:
\n\nSQLSTATE[23502]: Not null violation: (...)
Run Code Online (Sandbox Code Playgroud)
这是我收到的标题:
Allow ?GET, PUT, PATCH, DELETE
Cache-Control ?no-cache
Connection ?keep-alive
Content-Type ?application/json
Date ?Tue, 28 Oct 2014 14:30:10 GMT
Server ?nginx/1.1.19
Transfer-Encoding ?chunked
X-Debug-Token ?6d899c
X-Debug-Token-Link ?/api/_profiler/6d899c
X-Powered-By ?PHP/5.4.33-2+deb.sury.org~precise+1
Run Code Online (Sandbox Code Playgroud)
这是我的 PHP 代码
public function putAuthorAction(Request $request, $id)
{
try {
if (!($author …Run Code Online (Sandbox Code Playgroud) 我正在为我的JS驱动的应用程序制作REST API.
在登录期间,登录表单通过AJAX提交到/rest/login我的API的url .
虽然我已经为API和应用程序本身分离了防火墙,但它们共享相同的上下文,这应该意味着,当用户对API进行身份验证时,他也会针对应用程序进行身份验证.因此,当服务器返回204时,页面将重新加载,它应该将用户重定向到应用程序,因为他现在已登录.
我试图使用check_loginFOSUserBundle的预制页面并指向/rest/login那里.
login:
path: /rest/login
defaults:
_controller: FOSUserBundle:Security:check
methods: [ POST ]
Run Code Online (Sandbox Code Playgroud)
这不起作用,因为它总是返回重定向,无论如何.我阅读了symfony的文档,找不到如何制作自定义check_login页面.我需要的是这样的事情
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use FOS\RestBundle\Controller\Annotations\View;
class SecurityController {
/**
* @View(statusCode=204)
*/
public function loginAction($username, $password) {
/* first I need to somehow authenticate user
using normal authentication, that I've set up */
...
/* Then I need to return 204 or throw exception,
based on result.
This is done using FOSRestBundle and it's …Run Code Online (Sandbox Code Playgroud) php restful-authentication symfony fosuserbundle fosrestbundle
我目前正在使用 NelmioApiDocBundle,我对它还不是很熟悉。我正在编写的 API 必须提供更改特定用户密码的途径。文档应说明,更改密码既需要旧密码,也需要新密码。因为我没有发现之间的区别的解释Requirements和Parameters,我想首先是用于从路由数据,而后者用于API调用本身。
归档此类文档的第一次尝试是实现一个简单的模型,然后 JMSSerializerBundle 会自动转换该模型:
class ChangePasswordParam
{
/**
* @Type("string")
* @var string
*/
protected $oldPassword;
/**
* @Type("string")
* @var string
*/
protected $newPassword;
}
Run Code Online (Sandbox Code Playgroud)
Controller 通过这个 action 方法接受 API 调用:
/**
* Changes the password for a specific user.
*
* @Post("/{username}/changepassword")
* @View()
* @ApiDoc(
* description="Changes the password of a User",
* input="FQCN\ChangePasswordParam"
* )
*
* @param string $username
* @param ChangePasswordParam $passwordParam
*
* @return Response
*/ …Run Code Online (Sandbox Code Playgroud) php symfony fosrestbundle jmsserializerbundle nelmioapidocbundle
所以我正在使用 fosrestbundle fosuserbundle 和 LexikJWTAuthenticationBundle 构建一个 symfony2 api,当我想访问 /api/users.json 以发布新用户时,我收到 401 错误错误凭据。
我尝试以这种方式在访问控制中添加一行:
- { path: post_user, role: IS_AUTHENTICATED_ANONYMOUSLY }
Run Code Online (Sandbox Code Playgroud)
但它没有用。
我也试过:
- { path: post_user, role: IS_AUTHENTICATED_ANONYMOUSLY, methods:[POST] }
Run Code Online (Sandbox Code Playgroud)
我怎样才能只排除 post 端点?
我正在学习使用 symfony 构建 API(使用 FOSRestBundle)。我正在学习法语教程。显然,我首先尝试自己编写代码,但即使使用复制/粘贴,当我对适当的路由 (rest-api.local/places) 发出 GET 请求时,它也会让我得到空的 JSON 数组。
如果我在 php 数组中“格式化”代码,则代码可以正常工作:
public function getPlacesAction(Request $request)
{
$places = $this->get('doctrine.orm.entity_manager')
->getRepository('AppBundle:Place')
->findAll();
/* @var $places Place[] */
$formatted = [];
foreach ($places as $place) {
$formatted[] = [
'id' => $place->getId(),
'name' => $place->getName(),
'address' => $place->getAddress(),
];
}
return new JsonResponse($formatted);
}
Run Code Online (Sandbox Code Playgroud)
但后来我尝试使用 fost Rest 的视图处理程序(在 config.yml 中)直接序列化 $places
fos_rest:
routing_loader:
include_format: false
view:
view_response_listener: true
format_listener:
rules:
- { path: '^/', priorities: ['json'], fallback_format: 'json' } …Run Code Online (Sandbox Code Playgroud) 我尝试通过 Symfony (3.2) 中的表单验证来验证日期(或日期时间)。
我正在使用 FOSRestBundle 来使用请求中的 json (因为我尝试开发我的个人 API)
但我尝试了很多格式:
但表单无效,我总是收到此错误:此值无效
我的控制器的功能
public function postPlacesAction(Request $request) {
$place = new Place();
$form = $this->createForm(PlaceType::class, $place);
$form->handleRequest($request);
if ($form->isValid()) {
return $this->handleView($this->view(null, Response::HTTP_CREATED));
} else {
return $this->handleView($this->view($form->getErrors(), Response::HTTP_BAD_REQUEST));
}
}
Run Code Online (Sandbox Code Playgroud)
我的实体
class Place
{
/**
* @var string
*
* @Assert\NotBlank(message = "The name should not be blank.")
*/
protected $name;
/**
* @var string
*
* @Assert\NotBlank(message = "The address …Run Code Online (Sandbox Code Playgroud)