composer require server --dev
symfony server:start
bin/console debug:router
composer create-project symfony/website-skeleton:^4.4 rest_api_project
composer require symfony/maker-bundle --dev
bin/console doctrine:schema:create
bin/console make:controller
bin/console make:entity
composer require symfony/form
bin/console make:form
composer require api
composer create-project symfony/skeleton:^4.4 my_rest_api
move into project directory and execute the following:
composer require jms/serializer-bundle
composer require friendsofsymfony/rest-bundle
composer require sensio/framework-extra-bundle
composer require symfony/validator
composer require symfony/form
composer require symfony/orm-pack
In the .env file:
DATABASE_URL=mysql://db_user:[email protected]:3306/db_name?serverVersion=5.7
bin/console make:entity
bin/console doctrine:schema:create
bin/console make:form
Add the following to config/packages/fos_rest.yaml:
# Read the documentation: https://symfony.com/doc/master/bundles/FOSRestBundle/index.html
fos_rest:
routing_loader:
default_format: json
include_format: false
body_listener: true
format_listener:
rules:
- { path: '^/', priorities: ['json'], fallback_format: json, prefer_extension: false }
param_fetcher_listener: true
access_denied_listener:
json: true
view:
view_response_listener: 'force'
formats:
json: true
Add the following to the end of config/services.yaml:
sensio_framework_extra.view.listener:
alias: Sensio\Bundle\FrameworkExtraBundle\EventListener\TemplateListener
to address FOS/Sensio incompatibility: FriendsOfSymfony/FOSRestBundle#1768
eg: src/Controller/BookController.php
<?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\Book;
use App\Form\BookType;
/**
* Book controller.
* @Route("/api", name="api_")
*/
class BookController extends FOSRestController
{
/**
* Lists all Books.
* @Rest\Get("/books")
*
* @return Response
*/
public function getBookAction()
{
$repository = $this->getDoctrine()->getRepository(Book::class);
$books = $repository->findall();
return $this->handleView($this->view($books));
}
/**
* Create Book.
* @Rest\Post("/book")
*
* @return Response
*/
public function postBookAction(Request $request)
{
$book = new Book();
$form = $this->createForm(BookType::class, $book);
$data = json_decode($request->getContent(), true);
$form->submit($data);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($book);
$em->flush();
return $this->handleView($this->view(['status' => 'ok'], Response::HTTP_CREATED));
}
return $this->handleView($this->view($form->getErrors()));
}
}
composer require friendsofsymfony/rest-bundle
bin/console server:stop
bin/console make:controller