I have the following configuration:
fos_rest:
view:
view_response_listener: 'force'
formats:
json: true
xml: true
html: false
body_listener:
decoders:
json: fos_rest.decoder.json
xml: fos_rest.decoder.xml
body_converter:
enabled: true
format_listener:
enabled: true
rules:
- { path: '^/api', priorities: ['xml', 'json'], fallback_format: xml, prefer_extension: false }
param_fetcher_listener: force
routing_loader:
# default_format: xml
include_format: false
serializer:
serialize_null: true
and the following Controller:
/**
* #Rest\View(serializerGroups={"o-all-getCDashboard"})
*/
public function cgetAction($_format)
{
$handler = $this->getHandler();
die(dump($_format));
return $handler->getAll();
}
within a class that extends FOSRestController implements ClassResourceInterface
which always dumps null. If I re-enable default_format: xml what I get is always xml notwithstanding the Accept header I send. What's wrong with it? Why does not the format_listener work?
You using uncorrected format_listeners config.
Try using my config like this:
fos_rest:
body_listener: true
param_fetcher_listener: true
view:
view_response_listener: 'force'
formats:
jsonp: true
json: true
xml: false
rss: false
mime_types:
json: ['application/json', 'application/x-json']
jpg: ['image/jpeg']
png: ['image/png']
jsonp_handler: ~
routing_loader:
default_format: json
include_format: false
format_listener:
rules:
- { path: /api, priorities: [ json, jsonp ], fallback_format: json, prefer_extension: true }
exception:
enabled: true
Addition just settings section formats and fallback_format for yourself.
In my controller I using
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\Controller\Annotations\RouteResource;
/**
* #RouteResource("someName")
*/
class myController extends FOSRestController implements ClassResourceInterface {
/**
* #param Request $request
* #Rest\Post("/someLink")
*/
public function insertLinkAction(Request $request) {}
}
I hope that help you.
Related
I have tried the symfony4 with fos bundle rest api versioning and it url routing is working , but api versioning is not working. Please find my below code and i have missed out anything.
My Url :
example.com/v2/api/guesttest
example.com/v1/api/guesttest
when we accessing the above urls always returning the same set of reults v1.
Routes.yml
guest_api:
path: /{version}/api/guesttest
controller: App\Controller\TestController::test1
condition: "request.attributes.get('version') == 'v1'"
requirements:
version: 'v1|v2'
fos_rest.yaml
fos_rest:
param_fetcher_listener: true
allowed_methods_listener: true
routing_loader:
include_format: false
body_listener: true
format_listener:
rules:
- { path: ^/api, prefer_extension: false, fallback_format: json, priorities: [ json ] }
- { path: ^/, prefer_extension: true, fallback_format: html, priorities: [ html ] }
versioning:
enabled: true
default_version: v1
TestController.php
/**
* #Version("v1")
* #NamePrefix("v1")
*
*/
class TestController extends FOSRestController
{
public function test1()
{
return new Response("success....!");
exit;
}
}
jms_serializer.yaml
jms_serializer:
visitors:
xml:
format_output: '%kernel.debug%'
metadata:
cache: file
debug: "%kernel.debug%"
file_cache:
dir: "%kernel.cache_dir%/serializer"
auto_detection: true
Reference links:
github
Symfony-verioning
I am trying to setup the symfony3 codebase with FOS REST Bundle and I end up getting no route found error
AppBundle\Resources\config\api-routing.yml
check:
type: rest
resource: "#AppBundle/Controller/CheckController.php"
app\config\routing.yml
app:
type: rest
prefix: /
resource: '#AppBundle/Resources/config/api-routing.yml'
controller
namespace AppBundle\Controller;
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Controller\Annotations\Version;
use FOS\RestBundle\Controller\Annotations\RouteResource;
use Symfony\Component\HttpFoundation\Request;
/**
* #RouteResource("Check")
* #Version("v1")
*/
class CheckController extends FOSRestController
{
public function getAction(Request $request)
{
$data = "Ok";
return new JsonResponse($data);
}
}
http://127.0.0.1:8000/v1/app/check/ return no route
I would like to integrate the versioning of rest api route. Can you share what cud be the error and how can I correct this ?
fos_rest:
body_listener: true
versioning:
enabled: true
resolvers:
query:
enabled: true
parameter_name: version
format_listener:
rules:
- { path: '^/', priorities: ['json'], fallback_format: json, prefer_extension: false }
param_fetcher_listener: true
view:
view_response_listener: 'force'
formats:
json: true
Here is working example.
app\config\routng.yml
app:
type: rest
resource: "#AppBundle/Resources/config/routing.yml"
prefix: /api
AppBundle\Resources\config\routing.yml
rest_my:
type: rest
prefix: /v1
resource: "#AppBundle/Controller/MyRestController.php"
name_prefix: api_1_
Active route will be:
http://127.0.0.1:8000/api/v1/<MyRestControllerAction>
or for second controller
AppBundle\Resources\config\routing.yml
rest_user:
type: rest
prefix: /v1/user
resource: "#AppBundle/Controller/UserRestController.php"
name_prefix: api_1_
Active route will be:
http://127.0.0.1:8000/api/v1/user/<UserRestControllerAction>
I hope I help you... Chears.
Update #1:
Here is my complete fos_rest configuration for json format into config.yml file:
fos_rest:
routing_loader:
default_format: json
include_format: false
body_converter:
enabled: true
body_listener:
decoders:
json: fos_rest.decoder.json
format_listener:
enabled: true
rules:
- { path: '^/api/v1/', priorities: ['json'], fallback_format: json, prefer_extension: true}
- { path: '^/', priorities: ['json', 'html'], fallback_format: 'html' }
serializer:
serialize_null: true
view:
view_response_listener: 'force'
templating_formats:
html: false
param_fetcher_listener: 'force'
If you need more then that you have full documentation for fos_rest
http://symfony.com/doc/current/bundles/FOSRestBundle/configuration-reference.html
I am developing an application using Symfony2 with fos-restbundle. I would like to create some API routes and also some regular routes (exactly one for AngularJS front-end). This is my fos_rest configuration (and a few configuration lines from 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
As you can see i have view_response_listener enabled and view annotations disabled. I can't find the way to define "regular" (not REST) route (and view) for index action (neccesary for AngularJS). Keep getting an error:
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
I would appreciate any help with this.
You can add additional rule for your index page(for example):
format_listener:
rules:
- { path: '^/api', priorities: ['json', 'xml'], fallback_format: json, prefer_extension: true }
- { path: '^/', priorities: [ 'text/html', '*/*'], fallback_format: html, prefer_extension: true }
Read docs about format listener: http://symfony.com/doc/current/bundles/FOSRestBundle/format_listener.html
As suggested in the official docs you can also disable the format listener for the "normal" part of the site (not the APIs):
Often when integrating this Bundle with existing applications, it
might be useful to disable the format listener for some routes. In
this case it is possible to define a rule that will stop the format
listener from determining a format by setting stop to true as a rule
option. Any rule containing this setting and any rule following will
not be considered and the Request format will remain unchanged.
# app/config/config.yml
fos_rest:
format_listener:
enabled: true
rules:
- { path: '^/api', priorities: ['json', 'xml'], fallback_format: json, prefer_extension: false }
- { path: '^/', stop: true } # Available for version >= 1.5
the problem I am having is that all the error pages I configure in fos_rest only work in debug mode.
FOS\RestBundle\Controller\ExceptionController
The exception controller finds my custom Twig error pages from http://symfony.com/doc/current/cookbook/controller/error_pages.html correctly only when debug is enabled.
When I however disable debug mode, I am getting an exception thrown in https://github.com/FriendsOfSymfony/FOSRestBundle/blob/master/Controller/ExceptionController.php#L104
Twig is complaining that it's 404 even though it already figured out it's mapped.
My config:
fos_rest:
disable_csrf_role: ROLE_USER
routing_loader:
default_format: json
include_format: false
service:
exception_handler: fos_rest.view.exception_wrapper_handler
exception:
enabled: true
codes:
'Symfony\Component\Routing\Exception\ResourceNotFoundException': 404
'Symfony\Component\HttpKernel\Exception\NotFoundHttpException': 404
'Symfony\Component\Routing\Exception\ResourceNotFoundException': 404
'Symfony\Component\Security\Core\Exception\AccessDeniedException': 403
'Symfony\Component\Security\Core\Exception\DisabledException': 403
'Doctrine\DBAL\Exception\ServerException': 500
codes:
messages:
'Symfony\Component\Translation\Exception\NotFoundResourceException': false
'Symfony\Component\Security\Core\Exception\AccessDeniedException': true
'Symfony\Component\Security\Core\Exception\DisabledException': true
'Doctrine\DBAL\Exception\ServerException': false
body_listener: true
view:
view_response_listener: true
formats:
json: true
xml: false
html: true
templating_formats:
json: false
xml: false
html: true
force_redirects:
html: true
failed_validation: HTTP_BAD_REQUEST
default_engine: twig
format_listener:
rules:
- priorities: [json, html]
- fallback_format: json
- { path: '^/css', priorities: [ 'text/css', '*/*'], fallback_format: css, prefer_extension: true }
- { path: '^/api', priorities: [ 'json', 'text/html'], fallback_format: json, prefer_extension: false }
- { path: '^/', priorities: [ 'text/html', '*/*'], fallback_format: json, prefer_extension: false }
I'm having a problem with FOSRestBundle. Everything was working fine, until I added the #QueryParam annotation (on my cgetAction method) and the #ParamConverter annotation (on my getAction method). I have no idea what could be wrong, but the error I'm getting back is this...
The format "" is not supported for deserialization.
415 Unsupported Media Type - UnsupportedMediaTypeHttpException
The point of failure so to speak is here:
vendor\friendsofsymfony\rest-bundle\FOS\RestBundle\Request\AbstractRequestBodyParamConverter.php at line 118
My annotations for the specific controller are as follows (I'm just posting the cgetAction as I'm sure they are related somehow, I just don't know how)
/**
* Lists all School entities.
*
* #QueryParam(name="page", requirements="\d+", default="1", description="Current page of school listing")
* #View(template="LMSSchoolBundle:School:index.html.twig", templateVar="pagination")
*/
public function cgetAction(ParamFetcher $fetcher)
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('LMSSchoolBundle:School')->createQueryBuilder('s');
$pagination = $this->get('knp_paginator')->paginate(
$entities,
$fetcher->get('page'),
$this->container->getParameter('page_item_limit')
);
$groups = ($this->get('security.context')->isGranted('ROLE_API')) ? 'restapi' : 'standard';
$view = $this->view($pagination)
->getSerializationContext()
->setGroups($groups);
return $view;
}
And finally, the fos_rest section of my config.yml:
fos_rest:
routing_loader:
include_format: false
body_converter:
enabled: true
validate: true
validation_errors_argument: validationErrors
param_fetcher_listener: true
body_listener:
decoders:
json: fos_rest.decoder.jsontoform
xml: fos_rest.decoder.xml
allowed_methods_listener: true
access_denied_listener:
json: true
disable_csrf_role: ROLE_API
view:
formats:
json: true
rss: false
xml: true
templating_formats:
html: true
force_redirects:
html: true
failed_validation: HTTP_BAD_REQUEST
default_engine: twig
view_response_listener: 'force'
format_listener:
rules:
- { path: '^/css', priorities: [ 'css' ], fallback_format: false, prefer_extension: true }
- { path: '^/js', priorities: [ 'js' ], fallback_format: false, prefer_extension: true }
- { path: '^/', priorities: [ 'html', 'json', 'xml' ], fallback_format: html, prefer_extension: true }
- { path: '^/', host: 'api.%domain%', priorities: [ 'json', 'xml' ], fallback_format: json, prefer_extension: false }
NOTE - The ^/css and ^/js rules are in there because the bundle was messing with my layouts and such, don't know if that's the proper way to do it? I really don't know if this whole config section is even correct! The documentation is pretty complex, IMHO.
Anyway, if I remove the #QueryParam annotation, it continues into the function without an issue. But if I add it, the application exits before it even reaches $em = $this->...
Thanks for any help!
EDIT Oh and by the way, I have thought of the fact that this could be related to the JMSSerializer, but the website seems to be down at the moment (in South Africa at least), so yeah...