FOSRestBundle Documentation

repository·3.x·Indexed 25 days ago

https://github.com/friendsofsymfony/fosrestbundle

A Symfony bundle for rapid RESTful API development. It provides tools for format negotiation via Accept headers, request decoding, a view layer for format-agnostic controllers, and standardized error reporting compatible with RFC 7807. Key features include exception mapping to HTTP status codes, API versioning, and a suite of listeners for handling request bodies, mime types, and allowed HTTP methods.

Tokens
10.4K
Snippets
38
Records
61
Agent score
84%

What's inside FOSRestBundle

  1. Overview of FOSRestBundle features

    3.x

    FOSRestBundle is a Symfony bundle designed for rapid RESTful API development. It provides several core capabilities:

    • View Layer: Enables controllers to remain agnostic of the output format.
    • Format Negotiation: Handles Accept header negotiation, including support for custom mime types.
    • RESTful Decoding: Automatically decodes HTTP request bodies and Accept headers.
    • Exception Mapping: Maps exception codes directly to appropriate HTTP response status codes.
    • RFC 7807 Error Rendering: Provides a serializer error renderer that returns exceptions and errors in a format compatible with RFC 7807, utilizing either the Symfony Serializer or the JMS Serializer.
  2. Explore FOSRestBundle features

    3.x

    FOSRestBundle provides several loosely coupled tools for building REST applications with Symfony:

    • The view layer: Tools for managing how data is transformed into responses.
    • Listener support: Various listeners to handle request/response lifecycle events (e.g., format listeners, body listeners, versioning).
    • ExceptionController support: Support for handling exceptions within a REST context.
  3. Define REST-specific routes using HTTP method shortcuts

    3.x

    FOSRestBundle extends Symfony's @Route annotation by providing shortcuts for specific HTTP methods. These shortcuts support all standard @Route options.

    Available shortcuts include:

    • @Get, @Post, @Put, @Patch, @Delete
    • @Head, @Link, @Unlink, @Lock, @Unlock
    • @PropFind, @PropPatch, @Move, @Mkcol, @Copy
    // src/Controller/BlogController.php
    namespace App\
    Controller;
    
    use FOS\RestBundle\Controller\AbstractFOSRestController;
    use FOS\RestBundle\Controller\Annotations as Rest;
    
    class BlogController extends AbstractFOSRestController
    {
        /**
         * @Rest\Get("/blog", name="blog_list")
         */
        public function list()
        {
            // ...
        }
    }
    // Or using PHP 8 Attributes:
    
    class BlogController extends AbstractFOSRestController
    {
        #[Rest\Get('/blog', name: 'blog_list')]
        public function list()
        {
            // ...
        }
    }
  4. Handle Symfony Forms in the view layer

    3.x

    FOSRestBundle provides special handling for Symfony Forms. If you return a Form from a controller, set a Form as the view data, or return an array containing a 'form' key, the bundle automatically manages the response.

    If a bound form is invalid and no status code is explicitly set, the bundle will return a "validation failed" response (typically with a 400 status code) containing the error details in a structured format.

    // Example of an invalid form response structure:
    {
      "code": 400,
      "message": "Validation Failed",
      "errors": {
        "children": {
          "username": {
            "errors": [
              "This value should not be blank."
            ]
          }
        }
      }
    }
  5. Configure a Serializer for FOSRestBundle

    3.x

    FOSRestBundle requires a serializer to function. It automatically attempts to resolve a serializer in the following order of priority:

    1. A custom service configured via the fos_rest.service.serializer configuration key.
    2. The JMSSerializerBundle, if it is installed and registered.
    3. The Symfony Serializer, if it is enabled or if a service named serializer is available in the container.
  6. Enable and use object validation

    3.x

    To automatically validate the deserialized object, enable validate: true in the fos_rest.body_converter configuration.

    When validation is enabled, any errors found will be injected into a controller argument named after the validation_errors_argument configuration key (which defaults to validationErrors). You should type-hint this argument with ConstraintViolationListInterface.

    fos_rest:
        body_converter:
            enabled: true
            validate: true
            validation_errors_argument: validationErrors
    use Sensio\bundle\framework-extra-bundle\Configuration\ParamConverter;
    use Symfony\Component\Validator\Constraint\ConstraintViolationListInterface;
    
    /**
     * @ParamConverter("post", converter="fos_rest.request_body")
     */
    public function putPostAction(Post $post, ConstraintViolationListInterface $validationErrors)
    {
        if (count($validationErrors) > 0) {
            // Handle validation errors
        }
    
        // ...
    }
  7. Use the @View annotation for automatic response handling

    3.x

    If SensioFrameworkExtraBundle is installed and sensio_framework_extra.view.annotations is set to true, you can use the @View() annotation. This allows you to return raw data (like an array or object) from your controller instead of a View instance, as the listener will wrap the returned data into a view automatically.

    Note: The @View() annotation extends from the @Template() annotation provided by SensioFrameworkExtraBundle.

    <?php
    
    namespace AppBundle\
    Controller;
    
    use FOS\\RestBundle\\Controller\\Annotations\\View;
    
    class UsersController
    {
        /**
         * @View()
         */
        public function getUsersAction()
        {
            // ...
            return $data;
        }
    }