415 Unsupported Media Type - symfony

I followed this link
when I run this command to see if the Get method works very well I have this error displayed in my terminal ERROR 415: Unsupported Media Type.
I'm going to see my source code :
1- First I set my config file :
#app/config/config.yml
sensio_framework_extra:
view:
annotations: false
fos_rest:
param_fetcher_listener: true
body_listener: true
format_listener: true
view:
view_response_listener: 'force'
2- After i just fix my routing file :
#app/config/routing.yml
minn_ads_api:
resource: "#MinnAdsAPIBundle/Resources/config/routing.yml"
type: rest
3- I have also set the routing file in my *AdsAPIBundle :*
#AdsAPIBundle/Resources/config/routing.yml
brend:
type: rest
resource: Minn\AdsAPIBundle\Controller\BrendController
4- Under my AdsAPIBundle I just insert the function :
#src/BundleApi/Controller/BrendController.php
/**
* #Rest\View
* #Rest\Get("/api/brend/{id}", requirements={"id" = "\d+"}, defaults={"id" = 1})
*/
public function getAction($id) {
$repo = $this->getDoctrine()->
getManager()->
getRepository("MinnAdsBundle:Brend");
$brend = $repo->find($id);
return array('brend' => $brend);
}

Maybe you need to add a default format:
# app/config/config.yml
fos_rest:
routing_loader:
default_format: json

Related

Sonata Admin translations with default content

I was able to setup Sonata Admin with translated entities using Gedmo Doctrine Extensions:
# Doctrine Extensions Configuration
stof_doctrine_extensions:
default_locale: '%locale%'
orm:
default:
timestampable: true
blameable: true
translatable: true
# Sonata Translation Configuration
sonata_translation:
locales: [en, fr, it]
default_locale: '%locale%'
gedmo:
enabled: true
However every time I create a new entity, the translatable fields in the other languages starts empty.
English language selected:
Italian language selected:
It becomes very difficult to translate items if I don't know what they are in English.
Is there an option so that when I create an entity in English it populates also the entities in the other languages with the same content?
You should add fallback option to fields you need:
/**
* #var string
*
* #Assert\NotBlank()
*
* #Gedmo\Translatable(fallback=true)
*
* #ORM\Column(type="string", length=255)
*/
private $title;
I guess You forget to load the event listener service.
For each Gedmo extension (Timestampable, Blameable, Translatable etc. ) you have to register service in your service container.
For Translatable:
## app/config/services.yml
services:
## ...
gedmo.listener.translatable:
class: Gedmo\Translatable\TranslatableListener
tags:
- { name: doctrine.event_subscriber, connection: default }
calls:
- [ setAnnotationReader, [ #annotation_reader ] ]
- [ setDefaultLocale, [ %locale% ] ]
- [ setTranslationFallback, [ false ] ]

Why does a custom route appears twice in Nelmio API Doc?

I've tried defining a custom route name for one of my APIs and since then, the API Doc displays that route twice. Any ideas why?
Here's the definition of my API:
/**
* #ApiDoc(
* description = "Sends the support email to the HelpDesk address",
* statusCodes = {
* 204 = "Returned when successful",
* 400 = "Returned when the parameters are incorrect",
* 401 = "Returned when the token is invalid",
* 500 = "Returned when there's an internal server error"
* },
* input="AppBundle\Form\Type\SupportEmailType"
* )
* #Post("/support-requests")
* #Rest\View ()
*/
public function postSupportAction(Request $request)
and here's how the route shows up in my doc:
And this is my routing.yml file:
# app/config/routing.yml
app:
resource: "#AppBundle/Controller/"
type: annotation
NelmioApiDocBundle:
resource: "#NelmioApiDocBundle/Resources/config/routing.yml"
prefix: /api/doc
user:
type: rest
resource: AppBundle\Controller\UserController
From the looks of it the only thing that comes to mind as having the potential to do this is the first part of your routing.yml
try removing this from your routing.yml
app:
resource: "#AppBundle/Controller/"
type: annotation
I think this code, and the separated definition of the user route makes nelmio see the route twice. I had a similar problem some time ago and I think this was the reason. Sorry for the amount of questions I had to ask but i needed to see the full picture.
Hope this helps,
Alexandru Cosoi

Symfony with combination of Basic Routing and REST

My existing application requires additional RESTful endpoints.
I've added FOSRestBundle with the following configuration.
fos_rest:
param_fetcher_listener: true
view:
mime_types:
json: ['application/json', 'application/json;version=1.0', 'application/json;version=1.1', 'application/json;version=1.2']
view_response_listener: 'force'
formats:
xml: false
json: true
templating_formats:
html: false
format_listener:
rules:
- priorities: [json, xml]
- fallback_format: json
exception:
codes:
'Symfony\Component\Routing\Exception\ResourceNotFoundException': 404
'Doctrine\ORM\OptimisticLockException': HTTP_CONFLICT
messages:
'Symfony\Component\Routing\Exception\ResourceNotFoundException': true
allowed_methods_listener: true
access_denied_listener:
json: true
body_listener: true
routing_loader:
default_format: json
include_format: false
The REST requests are fine but the basic routing now doesn't work
With the following error
This page contains the following errors:
error on line 11 at column 92: EntityRef: expecting ';'
Below is a rendering of the page up to the first error.
Basically I just want to combine the basic routing with rest
You can solve this by disabling the format listener for your specific html routes (see http://symfony.com/doc/current/bundles/FOSRestBundle/format_listener.html#disabling-the-format-listener-via-rules)
So, add a rule for the format listener in your config.yml like this:
format_listener:
rules:
- { path: '^/my-html-routes', stop: true }
- { path: '^/api', priorities: ['json', 'xml'], fallback_format: json }

Symfony2 FOSRestBundle overrides default application

I'm using FOSRestBundle to manage my api. I already have a running sf2 application, and i want to allow third person to access some of my application features. I configured my api, and it works as expected, i can consume my api route with success
for example :
GET http://my.domain.ldt/api/v1/users
My Api only handle json format, here is my fos_rest configuration :
fos_rest:
param_fetcher_listener: true
body_listener: true
format_listener: true
view:
view_response_listener: 'force'
exception_wrapper_handler: My\ApiBundle\Handlers\ApiExceptionWrapperHandler
formats:
json : true
failed_validation: HTTP_BAD_REQUEST
templating_formats:
html: false
xml: false
routing_loader:
default_format: json
include_format: false
exception:
enabled: true
service:
view_handler: my.view_handler
services:
my.json_handler:
class: My\ApiBundle\Handlers\JsonHandler
my.view_handler:
parent: fos_rest.view_handler.default
calls:
- ['registerHandler', [ 'json', ["#my.json_handler", 'createResponse'] ] ]
As i said, my Api works well, but i face a major problem : When i try to access to the main application from my web browser, ( http://my.domain.ldt/, or http://my.domain.ldt/login), i get the following response instead of my classic web page :
An Exception was thrown while handling: No matching accepted Response format could be determined
Why my fos_rest conf applies on my main website ? Is it possible to only set the api conf for the api routes ? Did i miss something ?
The problem is that you forgot to define rules for FOSRestBundle's format listener.
In fact I'm not sure you need this listener as it seems you use json as the default format. The format listener will try to match the Accept header and extract the current request format based on it. So except if you want to support other formats than json for your api, you can just not use it.
In case you want to fix it instead of removing it, you have to update your config with something like:
fos_rest:
format_listener:
enabled: true
rules:
- { path: '^/', priorities: ['json', 'xml', 'html], fallback_format: 'json' }
Of course you can change this rule to have a different rule for your api:
fos_rest:
format_listener:
enabled: true
rules:
- { path: '^/api', fallback_format: 'json' }
- { path: '^/', fallback_format: 'html' }

symfony2: How to prevent FOSRestBundle from adding _api to route names and /api to urls?

I have an EventApiController class that looks like the following
Class EventApiController
{
public function getAction($event_id)
{
// ...
}
public function putAction($event_id)
{
// ...
}
}
Using the Friends of Symfony bundle's route generate i am expecting the route to look like
CalendarBundle_get_events [GET] /api/v1/events/{event_id}.{_format}
CalendarBundle_put_events [PUT] /api/v1/events/{event_id}.{_format}
However it seems like the Route generator automatically adds a post fix /api to all of the routes so the route looks like. And the documentation does not show this as the expected behaviour as well.
CalendarBundle_get_events_api [GET] /api/v1/events/{event_id}/api.{_format}
CalendarBundle_put_events_api [PUT] /api/v1/events/{event_id}/api.{_format}
Does anyone know how to get rid of the /api post fix from the generated link? I am using FOS/ResutBundle version 1.3.1
My config.yml for fos_rest
fos_rest:
routing_loader:
default_format: json
include_format: true
view:
view_response_listener: true
And the routing.yml looks like this in my Bundle
event_api:
type: rest
resource: "#CalendarBundle/Controller/EventsApiController.php"
prefix: /api/v1
name_prefix: CalendarBundle_
It's the Api in EventApiController that gets detected as route resource by FOSRestBundle.
You can override the resource name like this in order to prevent the _api route name and /api urls:
use FOS\RestBundle\Routing\ClassResourceInterface;
/**
* #RouteResource("Event")
*/
Class EventApiController implements ClassResourceInterface
{

Resources