### Versioned API Endpoint Example Source: https://context7.com/friendsofsymfony/fosrestbundle/llms.txt An example controller demonstrating how to handle versioned API requests and return different responses based on the detected API version. ```APIDOC ## Versioned API Endpoint Example ### Description This controller action demonstrates how to access the automatically set API version from the request attributes and return version-specific data. ### Method GET ### Endpoint /api/data ### Parameters #### Query Parameters - **version** (string) - Optional - Specifies the desired API version (e.g., `?version=2.0`). #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **data** (object) - The requested data payload. - **api_version** (string) - The version of the API that was served. #### Response Example ```json { "data": { "id": 1, "name": "Item", "metadata": { "created": "2024-01-01" } }, "api_version": "2.0" } ``` ```php attributes->get('version'); if ($version === '2.0') { return [ 'data' => ['id' => 1, 'name' => 'Item', 'metadata' => ['created' => '2024-01-01']], 'api_version' => '2.0' ]; } // Default v1.0 response return [ 'data' => ['id' => 1, 'name' => 'Item'], 'api_version' => '1.0' ]; } } ``` ``` -------------------------------- ### Using AbstractFOSRestController Source: https://github.com/friendsofsymfony/fosrestbundle/blob/3.x/Resources/doc/2-the-view-layer.md Example of how to use the `AbstractFOSRestController` to create and handle `View` objects in a controller action. ```APIDOC ## POST /api/users ### Description This endpoint demonstrates how to retrieve a list of users and return them as a formatted response using the FOSRestBundle view layer. ### Method GET ### Endpoint /api/users ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **data** (array) - A list of user objects. #### Response Example ```json [ { "id": 1, "username": "john_doe" }, { "id": 2, "username": "jane_smith" } ] ``` ``` -------------------------------- ### Complete FOSRestBundle Configuration Source: https://context7.com/friendsofsymfony/fosrestbundle/llms.txt A comprehensive configuration example covering body parsing, format negotiation, view layer settings, exception handling, and security. ```yaml fos_rest: param_fetcher_listener: force body_listener: enabled: true decoders: json: fos_rest.decoder.json xml: fos_rest.decoder.xml array_normalizer: fos_rest.normalizer.camel_keys format_listener: enabled: true rules: - { path: '^/api', priorities: ['json', 'xml'], fallback_format: json, prefer_extension: false } - { path: '^/', priorities: ['html', 'json'], fallback_format: html } view: view_response_listener: force formats: json: true xml: true html: true empty_content: 204 jsonp_handler: ~ mime_types: json: ['application/json', 'application/json;version=1.0'] exception: enabled: true codes: Symfony\Component\Routing\Exception\ResourceNotFoundException: 404 Symfony\Component\Security\Core\Exception\AccessDeniedException: 403 messages: Symfony\Component\HttpKernel\Exception\BadRequestHttpException: true versioning: enabled: true resolvers: query: true custom_header: true media_type: enabled: true regex: '/(v|version)=(?P[0-9\.]+)/' allowed_methods_listener: true disable_csrf_role: ROLE_API zone: - { path: '^/api/*' } ``` -------------------------------- ### FileParam Annotation Example Source: https://github.com/friendsofsymfony/fosrestbundle/blob/3.x/Resources/doc/param_fetcher_listener.md Shows how to use the `@FileParam` annotation for handling file uploads. ```APIDOC ## POST /api/upload ### Description This endpoint handles file uploads, accepting a file named 'fooFile'. ### Method POST ### Endpoint /api/upload ### Parameters #### Request Body - **fooFile** (file) - Required - The file to upload. Incompatible with the 'firstName' parameter. ### Request Example ```http POST /api/upload HTTP/1.1 Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW ------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="fooFile"; filename="example.txt" Content-Type: text/plain This is the content of the file. ------WebKitFormBoundary7MA4YWxkTrZu0gW-- ``` ### Response #### Success Response (200) - **filename** (string) - The name of the uploaded file. - **message** (string) - A success message. #### Response Example ```json { "filename": "example.txt", "message": "File uploaded successfully." } ``` ``` -------------------------------- ### Complete FOSRestBundle Configuration Source: https://context7.com/friendsofsymfony/fosrestbundle/llms.txt A comprehensive example showcasing all major features of FOSRestBundle working together, including param fetching, body parsing, format negotiation, view layer, exception handling, versioning, and zone restrictions. ```APIDOC ## Complete Bundle Configuration ### Description A comprehensive configuration example showing all major features working together. ### Method N/A (Configuration) ### Endpoint N/A (Configuration) ### Parameters N/A (Configuration) ### Request Example N/A (Configuration) ### Response N/A (Configuration) ```yaml # config/packages/fos_rest.yaml fos_rest: # Param fetcher listener param_fetcher_listener: force # Body listener for JSON/XML decoding body_listener: enabled: true decoders: json: fos_rest.decoder.json xml: fos_rest.decoder.xml array_normalizer: fos_rest.normalizer.camel_keys # Format negotiation format_listener: enabled: true rules: - { path: '^/api', priorities: ['json', 'xml'], fallback_format: json, prefer_extension: false } - { path: '^/', priorities: ['html', 'json'], fallback_format: html } # View layer view: view_response_listener: force formats: json: true xml: true html: true empty_content: 204 jsonp_handler: ~ mime_types: json: ['application/json', 'application/json;version=1.0'] # Exception handling exception: enabled: true codes: Symfony\Component\Routing\Exception\ResourceNotFoundException: 404 Symfony\Component\Security\Core\Exception\AccessDeniedException: 403 messages: Symfony\Component\HttpKernel\Exception\BadRequestHttpException: true # API versioning versioning: enabled: true resolvers: query: true custom_header: true media_type: enabled: true regex: '/(v|version)=(?P[0-9\.]+)/' # Allowed methods listener allowed_methods_listener: true # Disable CSRF for API users disable_csrf_role: ROLE_API # Zone restriction zone: - { path: '^/api/*' } ``` ``` -------------------------------- ### QueryParam Annotation Example Source: https://github.com/friendsofsymfony/fosrestbundle/blob/3.x/Resources/doc/param_fetcher_listener.md Demonstrates the usage of the `@QueryParam` annotation for defining and validating query parameters. ```APIDOC ## GET /api/resource ### Description This endpoint retrieves a resource, supporting pagination, item count limits, and sorting via query parameters. ### Method GET ### Endpoint /api/resource ### Parameters #### Query Parameters - **page** (string) - Optional - Page of the overview. Defaults to "1". - **count** (string) - Optional - Item count limit. If provided, requirements are strictly checked; otherwise, null is used. - **sort** (string) - Optional - Sort direction. Accepts "asc" or "desc". Defaults to "asc". - **ids[]** (integer) - Optional - List of IDs. Each ID is validated against the requirements. Defaults to `[1]` if not provided. - **filters** (object) - Optional - List of complex filters, validated by a custom constraint. ### Request Example ```http GET /api/resource?page=2&count=50&sort=desc&ids[]=1&ids[]=2&filters[key]=value ``` ### Response #### Success Response (200) - **data** (array) - The retrieved resource data. - **meta** (object) - Pagination and metadata. #### Response Example ```json { "data": [ { "id": 1, "name": "Example Item" } ], "meta": { "page": 2, "count": 50, "total": 100 } } ``` ``` -------------------------------- ### ParamFetcher Strict Mode and All Parameters Source: https://github.com/friendsofsymfony/fosrestbundle/blob/3.x/Resources/doc/param_fetcher_listener.md Explains the optional `$strict` parameter for `get()` and `all()` methods to throw RuntimeException on validation errors, and how to fetch all parameters at once. ```APIDOC ## ParamFetcher Strict Mode and All Parameters ### Description Enables strict validation mode for parameter fetching and provides a method to retrieve all configured parameters simultaneously. ### Method GET (or POST, depending on context) ### Endpoint Example endpoint: `/articles` ### Parameters #### Query Parameters - **(all)** - Fetches all configured query parameters. ### Request Example (Not applicable for strict mode explanation in this format) ### Response #### Success Response (200) - **articles** (array) - List of articles. - **page** (string) - The requested page number. #### Response Example ```json { "articles": ["bim", "bam", "bingo"], "page": "1" } ``` ``` -------------------------------- ### Route Conditions Based on Version Source: https://context7.com/friendsofsymfony/fosrestbundle/llms.txt Example of defining routes with conditions to route requests to specific controllers based on the API version. ```APIDOC ## Route Conditions Based on Version ### Description This configuration shows how to use route conditions in `config/routes.yaml` to direct traffic to different controller actions based on the resolved API version. ### Method N/A (Configuration) ### Endpoint N/A (Configuration) ### Parameters N/A (Configuration) ### Request Example N/A (Configuration) ### Response N/A (Configuration) ```yaml # config/routes.yaml - Route conditions based on version api_v2_users: path: /api/users controller: App\Controller\Api\V2\UserController::list condition: "request.attributes.get('version') == '2.0'" api_v1_users: path: /api/users controller: App\Controller\Api\V1\UserController::list ``` ``` -------------------------------- ### Install FOSRestBundle via Composer Source: https://github.com/friendsofsymfony/fosrestbundle/blob/3.x/Resources/doc/1-setting_up_the_bundle.md This command downloads and installs the latest stable version of the FOSRestBundle into your Symfony project. It requires Composer to be installed globally on your system. ```bash composer require friendsofsymfony/rest-bundle ``` -------------------------------- ### Dynamically Defining Serializer Options with View Context (PHP) Source: https://github.com/friendsofsymfony/fosrestbundle/blob/3.x/Resources/doc/view_response_listener.md Provides an example of dynamically setting serializer options, such as version and groups, using the View context. This offers more flexibility than static annotation configurations, allowing options to be determined at runtime. ```php setVersion('1.0'); $context->addGroup('user'); $view->setContext($context); // ... $view ->setData($data) ; return $view; } ``` -------------------------------- ### RequestParam Annotation Example Source: https://github.com/friendsofsymfony/fosrestbundle/blob/3.x/Resources/doc/param_fetcher_listener.md Illustrates the use of the `@RequestParam` annotation for handling parameters in the request body or form data. ```APIDOC ## POST /api/users ### Description This endpoint creates a new user, accepting first name and email address as request parameters. ### Method POST ### Endpoint /api/users ### Parameters #### Request Body - **firstname** (string) - Required - The user's first name. Must contain only lowercase letters. - **simpleEmail** (string) - Required - The user's email address. Must be a valid email format. - **complexEmail** (string) - Required - The user's email address. Must be a valid email format and not equal to "joe@example.org". - **nullableSample** (string) - Optional - A sample nullable field. - **search** (string) - Optional - Search term. - **byauthor** (string) - Optional - Filter by author. Incompatible with the 'search' parameter. ### Request Example ```json { "firstname": "john", "simpleEmail": "john.doe@example.com", "complexEmail": "john.doe@example.com", "nullableSample": "optional value" } ``` ### Response #### Success Response (201) - **id** (integer) - The ID of the newly created user. - **message** (string) - A success message. #### Response Example ```json { "id": 123, "message": "User created successfully." } ``` ``` -------------------------------- ### Configuring View with View Class Methods Source: https://github.com/friendsofsymfony/fosrestbundle/blob/3.x/Resources/doc/2-the-view-layer.md Illustrates various methods available on the `View` class for configuring the response, such as setting data, headers, status codes, serialization context, and redirect targets. ```php $view->setData($data); $view->setHeader($name, $value); $view->setHeaders(array $headers); $view->setStatusCode($code); $view->getContext(); $view->setContext($context); $view->setFormat($format); $view->setLocation($location); $view->setRoute($route); $view->setRouteParameters($parameters); $view->setResponse(Response $response); ``` -------------------------------- ### Controller Actions with FOSRestController Source: https://github.com/friendsofsymfony/fosrestbundle/blob/3.x/Resources/doc/2-the-view-layer.md Demonstrates how to use `AbstractFOSRestController` to create `View` instances for data responses and redirects, and then process them using `handleView`. ```php view($data, 200); return $this->handleView($view); } public function redirectAction() { $view = $this->redirectView($this->generateUrl('some_route'), 301); // or $view = $this->routeRedirectView('some_route', array(), 301); return $this->handleView($view); } } ``` -------------------------------- ### Query Parameters with ParamFetcher Source: https://github.com/friendsofsymfony/fosrestbundle/blob/3.x/Resources/doc/param_fetcher_listener.md Shows how to define and retrieve query parameters using @QueryParam, including requirements, default values, and descriptions. ```APIDOC ## Query Parameters with @QueryParam ### Description Defines and retrieves query parameters with validation rules and default values. ### Method GET ### Endpoint Example endpoint: `/articles` ### Parameters #### Query Parameters - **page** (string) - Optional - Defaults to '1' - Page of the overview. - **language** (string) - Optional - Defaults to the value of the '%locale%' container parameter. - **foo** (string) - Optional - Requirements based on the '%baz%' container parameter. - **val** (string) - Optional - Defaults to '75 %%'. ### Request Example (Not applicable for query parameters in this format) ### Response #### Success Response (200) - **articles** (array) - List of articles. - **page** (string) - The requested page number. #### Response Example ```json { "articles": ["bim", "bam", "bingo"], "page": "1" } ``` ``` -------------------------------- ### Handling Redirects with View Objects Source: https://github.com/friendsofsymfony/fosrestbundle/blob/3.x/Resources/doc/2-the-view-layer.md Demonstrates how to use `redirectView` and `routeRedirectView` to create redirect responses. ```APIDOC ## POST /redirect ### Description This endpoint shows how to create a redirect response to a specific URL or route using the FOSRestBundle view layer. ### Method GET ### Endpoint /redirect ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (301) - **Location** (string) - The URL to redirect to. #### Response Example ``` HTTP/1.1 301 Moved Permanently Location: /some/new/url ``` ``` -------------------------------- ### FOSRestBundle Route Annotations/Attributes Source: https://context7.com/friendsofsymfony/fosrestbundle/llms.txt Defines RESTful routes using HTTP method-specific annotations/attributes such as @Get, @Post, @Put, @Patch, and @Delete. ```APIDOC ## GET /posts ### Description Retrieves a list of all posts. ### Method GET ### Endpoint /posts ### Parameters None ### Request Example None ### Response #### Success Response (200) - **posts** (array) - A list of post objects. - **id** (integer) - The unique identifier of the post. - **title** (string) - The title of the post. #### Response Example ```json { "posts": [ { "id": 1, "title": "First Post" }, { "id": 2, "title": "Second Post" } ] } ``` ## GET /posts/{id} ### Description Retrieves a specific post by its ID. ### Method GET ### Endpoint /posts/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the post. ### Request Example None ### Response #### Success Response (200) - **id** (integer) - The unique identifier of the post. - **title** (string) - The title of the post. - **content** (string) - The content of the post. #### Response Example ```json { "id": 1, "title": "Post Title", "content": "Post content..." } ``` ## POST /posts ### Description Creates a new post. ### Method POST ### Endpoint /posts ### Parameters #### Request Body - **title** (string) - Required - The title of the new post. ### Request Example ```json { "title": "My New Post" } ``` ### Response #### Success Response (201) - **id** (integer) - The ID of the newly created post. - **title** (string) - The title of the newly created post. - **created** (boolean) - Indicates if the post was created successfully. #### Response Example ```json { "id": 3, "title": "My New Post", "created": true } ``` ## PUT /posts/{id} ### Description Updates an existing post. ### Method PUT ### Endpoint /posts/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the post to update. #### Request Body - **(Request body content depends on implementation, typically fields to update)** ### Request Example ```json { "title": "Updated Post Title" } ``` ### Response #### Success Response (200) - **id** (integer) - The ID of the updated post. - **updated** (boolean) - Indicates if the post was updated successfully. #### Response Example ```json { "id": 1, "updated": true } ``` ## DELETE /posts/{id} ### Description Deletes a specific post by its ID. ### Method DELETE ### Endpoint /posts/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the post to delete. ### Request Example None ### Response #### Success Response (204) No content. ## PATCH /posts/{id} ### Description Partially updates an existing post. ### Method PATCH ### Endpoint /posts/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the post to partially update. #### Request Body - **(Request body content depends on implementation, typically fields to update)** ### Request Example ```json { "title": "Partially Updated Title" } ``` ### Response #### Success Response (200) - **id** (integer) - The ID of the partially updated post. - **patched** (boolean) - Indicates if the post was patched successfully. #### Response Example ```json { "id": 1, "patched": true } ``` ``` -------------------------------- ### Enable FOSRestBundle Listeners (YAML) Source: https://github.com/friendsofsymfony/fosrestbundle/blob/3.x/Resources/doc/3-listener-support.md This YAML configuration demonstrates how to enable and configure several FOSRestBundle listeners, including the param_fetcher_listener, body_listener, and format_listener with custom rules. It also shows how to enable versioning and the view response listener. ```yaml fos_rest: param_fetcher_listener: true body_listener: true format_listener: enabled: true rules: - { path: '^/', priorities: ['json', 'xml'], fallback_format: 'html' } versioning: true view: view_response_listener: 'force' ``` -------------------------------- ### Apply EntityToIdObjectTransformer in FOSRestBundle Source: https://github.com/friendsofsymfony/fosrestbundle/blob/3.x/Resources/doc/2-the-view-layer.md Uses the EntityToIdObjectTransformer to allow forms to accept nested objects while mapping them to IDs, maintaining consistent data structures between GET and POST/PUT requests. ```php $personTransformer = new EntityToIdObjectTransformer($this->om, "AcmeDemoBundle:Person"); $builder ->add('name', 'text') ... ->add($builder->create('person', 'text')->addModelTransformer($personTransformer)); ``` -------------------------------- ### Configure Response Format Listener (YAML) Source: https://context7.com/friendsofsymfony/fosrestbundle/llms.txt Sets up the format listener to negotiate response formats based on Accept headers and configured priorities. This allows for automatic content-type selection without relying on file extensions. The configuration includes rules for API endpoints, image endpoints, admin sections, and public pages. ```yaml # config/packages/fos_rest.yaml fos_rest: format_listener: enabled: true rules: # API endpoints prefer JSON, fallback to XML - { path: '^/api', priorities: ['json', 'xml'], fallback_format: json, prefer_extension: false } # Image endpoints - { path: '^/images', priorities: ['jpeg', 'png', 'gif'], fallback_format: false, prefer_extension: true } # Admin section - XML and HTML - { path: '^/admin', methods: ['GET', 'POST'], priorities: ['xml', 'html'], fallback_format: html } # Public pages - HTML with any format fallback - { path: '^/', priorities: ['text/html', '*/*'], fallback_format: html, prefer_extension: true } # Stop format listener for legacy routes - { path: '^/legacy', stop: true } ``` -------------------------------- ### FOSRestBundle Routing Shortcuts Source: https://github.com/friendsofsymfony/fosrestbundle/blob/3.x/Resources/doc/annotations-reference.md Documentation for HTTP method-specific routing annotations that extend standard Symfony routing. ```APIDOC ## [HTTP_METHOD] [ENDPOINT] ### Description FOSRestBundle provides shortcuts for standard HTTP methods (GET, POST, PUT, DELETE, etc.) to define routes directly on controller methods. ### Method GET, POST, PUT, DELETE, etc. ### Endpoint Defined via the annotation path parameter. ### Request Example ```php #[Rest\Get('/blog', name: 'blog_list')] public function list() { ... } ``` ### Response #### Success Response (200) - **data** (mixed) - The returned resource or collection. ``` -------------------------------- ### Define Controller Parameters with Annotations Source: https://github.com/friendsofsymfony/fosrestbundle/blob/3.x/Resources/doc/param_fetcher_listener.md Use FOSRestBundle annotations to define, validate, and constrain query and request parameters within a Symfony controller. This example demonstrates usage of QueryParam, RequestParam, and FileParam with various validation constraints and mapping options. ```php 1, 'name' => 'John Doe', 'email' => 'john@example.com'], ['id' => 2, 'name' => 'Jane Smith', 'email' => 'jane@example.com'], ]; // Create a view with data and status code $view = $this->view($users, Response::HTTP_OK); // Convert view to response return $this->handleView($view); } public function postUserAction(): Response { // After creating a user, redirect to the new resource $view = $this->routeRedirectView('get_user', ['id' => 123], Response::HTTP_CREATED); return $this->handleView($view); } public function deleteUserAction(int $id): Response { // Return 204 No Content on successful deletion $view = $this->view(null, Response::HTTP_NO_CONTENT); return $this->handleView($view); } } ``` -------------------------------- ### Returning a View Instance from Controller Action (PHP) Source: https://github.com/friendsofsymfony/fosrestbundle/blob/3.x/Resources/doc/view_response_listener.md Demonstrates how to return a FOSRestBundle View instance from a controller action. This View object is then processed by the listener to generate the final response. Requires SensioFrameworkExtraBundle. ```php setData($data); return $view; } } ``` -------------------------------- ### Handling File Uploads with ParamFetcher Source: https://github.com/friendsofsymfony/fosrestbundle/blob/3.x/Resources/doc/param_fetcher_listener.md Demonstrates how to use @FileParam annotation to handle file uploads with specific requirements like MIME types, size limits, and image dimensions. It also shows how to provide a default value if the file is not an image. ```php name = "dynamic_request"; $dynamicRequestParam->requirements = "\\d+"; $paramFetcher->addParam($dynamicRequestParam); $dynamicQueryParam = new QueryParam(); $dynamicQueryParam->name = "dynamic_query"; $dynamicQueryParam->requirements = "[a-z]+"; $paramFetcher->addParam($dynamicQueryParam); $page = $paramFetcher->get('page'); $articles = array('bim', 'bam', 'bingo'); return array('articles' => $articles, 'page' => $page); } } ``` -------------------------------- ### Using Container Parameters with ParamFetcher Source: https://github.com/friendsofsymfony/fosrestbundle/blob/3.x/Resources/doc/param_fetcher_listener.md Shows how to utilize container parameters within the 'requirements' and 'default' fields of @QueryParam annotations. It also demonstrates escaping the percent sign when it's part of the default value. ```php array( 'application/json', ), 'yml' => array( 'application/yaml', 'text/yaml', ), ); array_walk($mimeTypes, function (&$mimeTypes, $format, $versions) { $versionMimeTypes = array(); foreach ($mimeTypes as $mimeType) { foreach ($versions as $version) { array_push($versionMimeTypes, sprintf('%s;version=%s', $mimeType, $version)); array_push($versionMimeTypes, sprintf('%s;v=%s', $mimeType, $version)); } } $mimeTypes = array_merge($mimeTypes, $versionMimeTypes); }, $versions); $container->loadFromExtension('fos_rest', array( 'view' => array( 'mime_types' => $mimeTypes, ), )); ``` ```yaml imports: - { resource: fos_rest_mime_types.php } ``` -------------------------------- ### Dynamic Parameter Addition Source: https://github.com/friendsofsymfony/fosrestbundle/blob/3.x/Resources/doc/param_fetcher_listener.md Illustrates how to dynamically add request and query parameters to the ParamFetcher at runtime. ```APIDOC ## Dynamic Parameter Addition ### Description Allows adding request and query parameters to the ParamFetcher dynamically during runtime. ### Method GET (or POST, depending on context) ### Endpoint Example endpoint: `/articles` ### Parameters #### Query Parameters (Dynamically Added) - **dynamic_request** (string) - Requirements: `\d+`. - **dynamic_query** (string) - Requirements: `[a-z]+`. ### Request Example (Not applicable for dynamic parameter addition in this format) ### Response #### Success Response (200) - **articles** (array) - List of articles. - **page** (string) - The requested page number. #### Response Example ```json { "articles": ["bim", "bam", "bingo"], "page": "1" } ``` ``` -------------------------------- ### Basic Query Parameter Handling with ParamFetcher Source: https://github.com/friendsofsymfony/fosrestbundle/blob/3.x/Resources/doc/param_fetcher_listener.md Illustrates how to define and retrieve a simple query parameter named 'page' using the @QueryParam annotation. The parameter is expected to be a digit and defaults to '1'. ```php $articles, 'page' => $page); } } ``` -------------------------------- ### URI Routing for API Versioning Source: https://github.com/friendsofsymfony/fosrestbundle/blob/3.x/Resources/doc/versioning.md Demonstrates how to define routes in Symfony's router that include a version parameter in the URI path. This approach allows for version-specific endpoints. ```yaml my_route: path: /{version}/foo/route ``` -------------------------------- ### Configure FOSRestBundle Versioning Source: https://github.com/friendsofsymfony/fosrestbundle/blob/3.x/Resources/doc/versioning.md Enables API versioning in FOSRestBundle and configures which version resolvers to use (query, custom header, media type). It also shows how to set the guessing order for these resolvers. ```yaml fos_rest: versioning: enabled: true resolvers: query: true custom_header: true media_type: enabled: true regex: '/(v|version)=(?P[0-9\.]+)/' guessing_order: - query - custom_header - media_type ``` -------------------------------- ### ParamFetcher Listener Configuration Source: https://github.com/friendsofsymfony/fosrestbundle/blob/3.x/Resources/doc/param_fetcher_listener.md Configuration snippet to enable the ParamFetcher listener, which can automatically set configured query parameters as request attributes. ```yaml fos_rest: param_fetcher_listener: force ``` -------------------------------- ### Using @View Annotation for Simplified Response Handling (PHP) Source: https://github.com/friendsofsymfony/fosrestbundle/blob/3.x/Resources/doc/view_response_listener.md Shows how to use the @View annotation provided by FOSRestBundle (in conjunction with SensioFrameworkExtraBundle) to simplify response handling. The annotation automatically creates and configures a View instance, allowing the controller to directly return data. ```php setFormat('html'); } ``` -------------------------------- ### Customize Body Listener Service (YAML) Source: https://github.com/friendsofsymfony/fosrestbundle/blob/3.x/Resources/doc/3-listener-support.md This YAML configuration shows how to replace the default service used by the body listener with a custom service. It defines the custom service 'my_body_listener' with its class, event listener tags, arguments, and method calls. ```yaml fos_rest: body_listener: service: my_body_listener my_body_listener: class: Acme\BodyListener tags: - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest, priority: 10 } arguments: ['@fos_rest.decoder_provider', '%fos_rest.throw_exception_on_unsupported_content_type%'] calls: - [setDefaultFormat, ['%fos_rest.body_default_format%']] ``` -------------------------------- ### Param Fetcher Listener Configuration Source: https://github.com/friendsofsymfony/fosrestbundle/blob/3.x/Resources/doc/param_fetcher_listener.md This snippet shows how to enable the Param Fetcher Listener in your FOSRestBundle configuration. ```APIDOC ## Param Fetcher Listener Configuration ### Description Enable the Param Fetcher Listener to automatically inject and configure `ParamFetcher` instances for your controllers. ### Method N/A (Configuration) ### Endpoint N/A (Configuration) ### Parameters N/A (Configuration) ### Request Example ```yaml fos_rest: param_fetcher_listener: true ``` ### Response N/A (Configuration) ``` -------------------------------- ### FOSRestBundle Parameter Annotations Source: https://github.com/friendsofsymfony/fosrestbundle/blob/3.x/Resources/doc/annotations-reference.md Defines how to use QueryParam, RequestParam, and FileParam to validate and fetch input parameters in your controllers. ```APIDOC ## Parameter Fetching Annotations ### Description FOSRestBundle provides annotations to automatically validate and fetch parameters from queries, request bodies, or file uploads. ### Parameters - **name** (string) - Required - The name of the parameter. - **requirements** (string/array) - Optional - Validation requirements (regex or constraints). - **default** (mixed) - Optional - Default value if parameter is missing. - **strict** (boolean) - Optional - Whether to throw an exception if the parameter is invalid. ### Example ```php #[QueryParam(name: 'page', requirements: '\\d+', default: 1)] #[RequestParam(name: 'username', strict: true)] #[FileParam(name: 'avatar', image: true)] ``` ``` -------------------------------- ### Throwing HTTP Exceptions in Controllers Source: https://github.com/friendsofsymfony/fosrestbundle/blob/3.x/Resources/doc/4-exception-controller-support.md Demonstrates how to throw `HttpException` instances with custom status codes and messages within a controller. ```APIDOC ## Throwing HTTP Exceptions in Controllers ### Description Throw `Symfony\Component\HttpKernel\Exception\HttpException` instances directly within your controller actions to return specific HTTP error responses. ### Method PHP Controller Action ### Endpoint Example: `POST /users/{slug}/comments` ### Parameters #### Path Parameters - **slug** (string) - Required - The identifier for the user. #### Query Parameters None #### Request Body None (for this specific example) ### Request Example N/A (Controller logic) ### Response #### Success Response (200) - N/A (This example focuses on error handling) #### Error Response (e.g., 400 Bad Request) - **message** (string) - The error message provided in the `HttpException`. ### Code Example ```php validate($slug)) { throw new HttpException(400, "New comment is not valid."); } // ... proceed with creating user comments ... } // Dummy validate method for example purposes private function validate($slug) { // Replace with actual validation logic return $slug !== null; } } ``` ```