Step 1. Set up FOSRestBundle

	
$ composer require friendsofsymfony/rest-bundle

Step 2. Install symfony serializer

composer require symfony/serializer

Step 3. Configure the config/packages/fos_rest.yaml

fos_rest:
    param_fetcher_listener: true
    body_listener: true
    format_listener:
        enabled: true
        rules:
            #- { path: '^/', priorities: ['json', 'xml'], fallback_format: 'html'}
            - { path: '^/', priorities: ['json'], fallback_format: json, prefer_extension: false }
    versioning: true
    view:
        view_response_listener: 'force'
    zone:
        - { path: ^/api/* }

Step 4. Configure config/services.yaml . We have to add the following code in the bottom

    sensio_framework_extra.view.listener:
        alias: Sensio\Bundle\FrameworkExtraBundle\EventListener\TemplateListener

Step 5. Create a Apicontroller

<?php
namespace App\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Controller\Annotations as Rest;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use App\Entity\User;

/**
 * Api controller.
 * @Route("/api", name="api_")
 */
class ApiController extends FOSRestController
{
  /**
   * Lists all users.
   * @Rest\Get("/users")
   *
   * @return Response
   */
  public function getUsers()
  {
    $repository = $this->getDoctrine()->getRepository(User::class);
    $users = $repository->findall();
    $list = array();
    foreach ($users as $user) {
      $list[] = $school->getName();
    }

    return $this->handleView($this->view($list));
  }

}

Read More https://symfony.com/doc/master/bundles/FOSRestBundle/index.html

Another document https://www.adcisolutions.com/knowledge/getting-started-rest-api-symfony-4

By toihid

Leave a Reply