Service approach for
development Rest API in
Symfony2
Aleksey Kryvtsov @ Web-developer at CPCS
alkryvtsov@gmail.com
Development Rest API in Symfony2
2
● Interface as contracts.
● Thin Controller, Fat Service.
● The Content Negotiation in the HTTP and REST.
● Form as API interface.
Rules
3
● FOSRestBundle
● JMSSerializerBundle
● NelmioApiDocBundle
List of bundles
// app/AppKernel.php
$bundles = [
//...
new FOSRestBundleFOSRestBundle(),
new JMSSerializerBundleJMSSerializerBundle(),
new
NelmioApiDocBundleNelmioApiDocBundle(),
4
/api/v1/{_lang}/pages/{id}.{_format}
/api/v1/en/pages/{id}.json
Will return a json file
/api/v1/en/pages/{id}.xml
Will return a xml file
/api/v1/en/pages/{id} and /api/v1/en/pages/{id}.html
Will return the web page file
Format of routing
5
# /app/config/routing.yml
acme_api_blog:
type: rest
prefix: /api/v1/{_lang}
resource:
"@AcmeBlogBundle/Resources/config/routes.yml"
Adding the routes
6
# /src/Acme/BlogBundle/Resources/config/routes.yml
acme_api_blog_page:
resource:
"AcmeBlogBundleControllerPageController"
name_prefix: api_v1_ # naming collision
Create a route file into the bundle
# php app/console route:debug | grep api_v1_
7
# /src/Acme/BlogBundle/Controller/PageController.php
namespace AcmeBlogBundleController;
use FOSRestBundleControllerFOSRestController as Rest;
class PageController extends Rest {
// another methods POST, PUT, DELETE and etc...
/* @annotations */
public function getPageAction ($id) {
return $this->get('acme_blog.blog_post.handler')->get($id);
}
}
Controller: PageController::getPageAction ()
8
# /src/Acme/BlogBundle/Controller/PageController.php
use FOSRestBundleControllerAnnotations as FOSRest;
/**
* Get single Page
* @FOSRestGet("/pages/{id}", requirements={"id" = "d+"}, name="get_page")
* @FOSRestView(serializerGroups={"page"})
*
* @ApiDoc(/* documentation */)
*
* @param int $id The page id
*
* @return array
* @throws NotFoundHttpException when page not exist or not found
*/
public function getPageAction ($id) {}
Controller: PageController::getPageAction ()
9
# /src/Acme/BlogBundle/Entity/Page.php
namespace AcmeBlogBundleEntity;
class Page implements PageInterface {
// fields, getters and setters
}
Interface as contract
# /src/Acme/BlogBundle/Model/PageInterface.php
namespace AcmeBlogBundleModel;
interface PageInterface {
}
10
Handler configuration. Part I
# /src/Acme/BlogBundle/Resources/config/handlers.yml
services:
1 acme_blog.page.entity:
class: AcmeBlogBundleEntityPage
2 acme_blog.blog_post.handler:
class: AcmeBlogBundleHandlerPageHandler
arguments:
3 - @doctrine.orm.entity_manager
4 - @acme_blog.page.entity
11
HandlerInterface: PageHandlerInterface::get()
# /src/Acme/BlogBundle/Handler/PageHandlerInterface.php
namespace AcmeBlogBundleHandler;
use AcmeBlogBundleModelPageInterface;
interface PageHandlerInterface {
// another methods POST, PUT, DELETE and etc...
/**
* Gets a page by id
*
* @api
* @param integer $id
*
* @return PageInterface
*/
public function get ($id);
}
12
Handler: PageHandler::__construct()
# /src/Acme/BlogBundle/Handler/PageHandler.php
namespace AcmeBlogBundleHandler;
use DoctrineORMEntityManager;
use AcmeBlogBundleModelPageInterface;
class PageHandler implements PageHandlerInterface {
// another methods
/**
* @return void
*/
public function __construct(
EntityManager $entityManager,
PageInterface $pageEntity
) // continue...
13
Handler: PageHandler::__construct()
# /src/Acme/BlogBundle/Handler/PageHandler.php
namespace AcmeBlogBundleHandler;
class PageHandler implements PageHandlerInterface {
// another methods
/* public function __construct (...) */ {
1 $this->entityManager = $entityManager;
2 $this->pageEntity = $pageEntity;
3 $this->repository = $entityManager->getRepository(get_class($pageEntity));
}
}
14
Handler: PageHandler (UML)
15
Handler: PageHandler::get()
# /src/Acme/BlogBundle/Handler/PageHandler.php
namespace AcmeBlogBundleHandler;
class PageHandler implements PageHandlerInterface {
// another methods POST, PUT, DELETE and etc...
/**
* {@inheritdoc}
*/
public function get ($id) {
return $this->repository->find($id);
}
}
16
Controller: PageController::getAllPagesAction()
17
URL: ~/pages
18
Diagram: getAction, getAllAction
# /src/Acme/BlogBundle/Controller/PageController.php
use SymfonyComponentHttpFoundationRequest;
class PageController extends Rest {
// another methods
/* @annotations -> URL: ~/pages */
public function postPageAction(Request $request) {
return $this->get('acme_blog.blog_post.handler')
->post($request->request->all());
}
}
Controller: PageController::postPageAction ()
19
HandlerInterface: PageHandlerInterface::post()
# /src/Acme/BlogBundle/Handler/PageHandlerInterface.php
use AcmeBlogBundleModelPageInterface;
interface PageHandlerInterface {
/**
* Creates a new page
*
* @api
* @param array $parameters
* @param array $options
*
* @return PageInterface
*/
public function post(array $parameters = [], array $options = []);
}
20
Handler: PageHandler::post()
# /src/Acme/BlogBundle/Handler/PageHandler.php
/* {@inheritdoc} */
public function post (
array $parameters = [],
array $options = []
) {
return $this->processForm(
$this->pageClass,
$parameters,
$options,
“POST”
);
}
21
Handler configuration. Part II
# /src/Acme/BlogBundle/Resources/config/handlers.yml
services:
// ...
acme_blog.page.form_type:
class: AcmeBlogBundleFormTypePageFormType
acme_blog.blog_post.handler:
class: AcmeBlogBundleHandlerPageHandler
arguments:
- @doctrine.orm.entity_manager
- @acme_blog.page.entity
- @form.factory
- @acme_blog.page.form_type
22
Handler: PageHandler::__construct()
# /src/Acme/BlogBundle/Handler/PageHandler.php
use SymfonyComponentFormFormFactoryInterface;
use use SymfonyComponentFormFormTypeInterface;
class PageHandler implements PageHandlerInterface {
/**
* @return void
*/
public function __construct (
//...
FormFactoryInterface $formFactory,
FormTypeInterface $formType
) {
// ...
$this->formFactory = $formFactory;
$this->formType = $formType;
} 23
HandlerInterface: PageHandlerInterface::processForm()
# /src/Acme/BlogBundle/Handler/PageHandlerInterface.php
use AcmeBlogBundleModelPageInterface;
interface PageHandlerInterface {
/**
* Processes the form
*
* @api
* @param PageInterface $page
* @param array $parameters
* @param array $options
* @param string $method
*
* @return PageInterface
*/
private function processForm(PageInterface $page, array $parameters = [], array $options = [],
$method
)
} 24
Handler: PageHandler::processForm()
# /src/Acme/BlogBundle/Handler/PageHandler.php
protected function processForm (/*...*/) {
1 $form = $this->formFactory->create($this->formType, $page, $options);
2 $form->submit($parameters, 'PATCH' !== $method);
3 if ($form->isValid()) {
4 $this->entityManager->persist($page);
5 $this->entityManager->flush($page);
6 return $page;
}
7 // throw new InvalidFormException(/*...*/)
}
25
Controller: PageController::[patch|put]PageAction()
26
URL: ~/pages/{id}
Handler: PageHandler::patch()
# /src/Acme/BlogBundle/Handler/PageHandler.php
// another methods
public function patch(array $parameters = [], array $options = []) {
1 $page = $this->get($parameters[‘id’]);
2 return $this->processForm(
$page,
$parameters,
$options,
“PATCH”
);
}
27
Handler: PageHandler::put()
# /src/Acme/BlogBundle/Handler/PageHandler.php
// another methods
public function put(array $parameters = [], array $options = []) {
1 $page = $this->get($parameters[‘id’]);
2 return $this->processForm(
$page,
$parameters,
$options,
“PUT”
);
}
28
29
Diagram: postAction, putAction, patchAction
# /src/Acme/BlogBundle/Controller/PageController.php
class PageController extends Rest {
// another methods
/* @annotations -> URL: ~/pages/{id} */
public function deletePageAction($id) {
return $this->get('acme_blog.blog_post.handler')->delete($id);
}
}
Controller: PageController::deletePageAction()
30
HandlerInterface: PageHandlerInterface::delete()
# /src/Acme/BlogBundle/Handler/PageHandlerInterface.php
use AcmeBlogBundleModelPageInterface;
interface PageHandlerInterface {
/**
* Returns the result of removal
*
* @api
* @param integer $id
*
* @return string
*/
public function delete($id);
}
31
Handler: PageHandler::delete()
# /src/Acme/BlogBundle/Handler/PageHandler.php
namespace AcmeBlogBundleHandler;
class PageHandler implements PageHandlerInterface {
/**
* {@inheritdoc}
*/
public function delete ($id) {
1 $page = $this->get($id);
2 $this->entityManager->remove($page);
3 $this->entityManager->flush();
}
}
32
Diagram
33
34
UML
1. # app/config/routing.yml
NelmioApiDocBundle:
resource: "@NelmioApiDocBundle/Resources/config/routing.yml"
prefix: /api/doc
Documentation: ApiDoc
35
2. # /src/Acme/BlogBundle/Controller/PageController.php
/**
* @ApiDoc(
* description = "Creates a new page from the submitted data.",
* input = "AcmeBlogBundleFormPageType",
* output = "AcmeBlogBundleEntityPage",
* statusCodes = {
* 200 = "Returned when successful",
* 400 = "Returned when the form has errors"
* }
* )
*/
36
JMSSerializer
37
# /src/Acme/BlogBundle/Entity/Page.php
use DoctrineORMMapping as ORM;
use JMSSerializerAnnotation as JMS;
/**
* @ORMEntity
* @JMSExclusionPolicy("all")
*/
class Page {
/**
* @JMSExpose
* @JMSType("AnotherClass")
* @JMSGroups({"page", "details"})
* @ORMManyToOne(targetEntity="AnotherClass")
* @ORMJoinColumn(name="column", referencedColumnName="id")
*/
protected $field;
{
"id": 1,
"field": AnotherClass,
"another": "anotherType"
}
JMSSerializer: Annotations
38
● @ExclusionPolicy
● @Exclude
● @Expose
● @SerializedName
● @Since
● @Until
● @Groups
● @MaxDepth
● @AccessType
● @Accessor
● @ReadOnly
● @PreSerialize
● @PostSerialize
● @PostDeserialize
● @HandlerCallback
● @Discriminator
● @Type
● @XmlRoot
● @XmlAttribute
● @XmlValue
References
http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api
Best Practices for Designing a Pragmatic RESTful API
http://williamdurand.fr/2012/08/02/rest-apis-with-symfony2-the-right-way
REST APIs with Symfony2: The Right Way
https://www.youtube.com/watch?v=Kkby5fG89K0
Lukas Kahwe Smith (Symfony Camp)
http://welcometothebundle.com/symfony2-rest-api-the-best-2013-way
Symfony2 REST API: the best way
https://github.com/liuggio/symfony2-rest-api-the-best-2013-way
The github repository
39
Thank you
Questions ?
Aleksey Kryvtsov alkryvtsov@gmail.com
40

More Related Content

PPTX
Service approach for development Rest API in Symfony2
PDF
REST in practice with Symfony2
PDF
Bootstrat REST APIs with Laravel 5
PPTX
REST APIs in Laravel 101
PDF
Bullet: The Functional PHP Micro-Framework
PDF
Codeigniter : Two Step View - Concept Implementation
PDF
Laravel 로 배우는 서버사이드 #5
PDF
Getting Started-with-Laravel
Service approach for development Rest API in Symfony2
REST in practice with Symfony2
Bootstrat REST APIs with Laravel 5
REST APIs in Laravel 101
Bullet: The Functional PHP Micro-Framework
Codeigniter : Two Step View - Concept Implementation
Laravel 로 배우는 서버사이드 #5
Getting Started-with-Laravel

What's hot (20)

ODP
Javascript laravel's friend
PDF
Action Controller Overview, Season 2
PDF
170517 damien gérard framework facebook
PPT
Building Single Page Application (SPA) with Symfony2 and AngularJS
ODP
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
PDF
AngularJS with Slim PHP Micro Framework
PPTX
Zend framework
PPT
Workshop: Symfony2 Intruduction: (Controller, Routing, Model)
KEY
More to RoC weibo
PDF
浜松Rails3道場 其の壱 プロジェクト作成〜Rouging編
KEY
Rails web api 开发
PPTX
Laravel 5
PDF
ACL in CodeIgniter
PDF
RESTful API development in Laravel 4 - Christopher Pecoraro
PDF
Layouts and Rendering in Rails, Season 2
PDF
Action View Form Helpers - 1, Season 2
PPT
Red5 - PHUG Workshops
PDF
Flask patterns
PDF
The new features of PHP 7
PDF
Keeping it Small: Getting to know the Slim Micro Framework
Javascript laravel's friend
Action Controller Overview, Season 2
170517 damien gérard framework facebook
Building Single Page Application (SPA) with Symfony2 and AngularJS
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
AngularJS with Slim PHP Micro Framework
Zend framework
Workshop: Symfony2 Intruduction: (Controller, Routing, Model)
More to RoC weibo
浜松Rails3道場 其の壱 プロジェクト作成〜Rouging編
Rails web api 开发
Laravel 5
ACL in CodeIgniter
RESTful API development in Laravel 4 - Christopher Pecoraro
Layouts and Rendering in Rails, Season 2
Action View Form Helpers - 1, Season 2
Red5 - PHUG Workshops
Flask patterns
The new features of PHP 7
Keeping it Small: Getting to know the Slim Micro Framework

Viewers also liked (20)

PPTX
Symfony2 Authentication
PPTX
Building a Website to Scale to 100 Million Page Views Per Day and Beyond
PDF
$kernel->infect(): Creating a cryptovirus for Symfony2 apps
PDF
Autenticazione delle api con jwt e symfony (Italian)
PDF
Building a documented RESTful API in just a few hours with Symfony
PDF
Be RESTful (Symfony Camp 2008)
PPTX
Http and REST APIs.
PDF
Scaling Symfony2 apps with RabbitMQ - Symfony UK Meetup
PDF
Love and Loss: A Symfony Security Play
PDF
A high profile project with Symfony and API Platform: beIN SPORTS
ODP
Rich domain model with symfony 2.5 and doctrine 2.5
PDF
Présentation sur l'accessibilité numérique / Evènement université de Lille 3
PDF
Symfony Guard Authentication: Fun with API Token, Social Login, JWT and more
PDF
30 Symfony Best Practices
PDF
Symfony in microservice architecture
PPTX
Creating hypermedia APIs in a few minutes using the API Platform framework
PDF
Symfony: Your Next Microframework (SymfonyCon 2015)
PDF
New Symfony Tips & Tricks (SymfonyCon Paris 2015)
PPTX
Single-Page-Application & REST security
PDF
Symfony tips and tricks
Symfony2 Authentication
Building a Website to Scale to 100 Million Page Views Per Day and Beyond
$kernel->infect(): Creating a cryptovirus for Symfony2 apps
Autenticazione delle api con jwt e symfony (Italian)
Building a documented RESTful API in just a few hours with Symfony
Be RESTful (Symfony Camp 2008)
Http and REST APIs.
Scaling Symfony2 apps with RabbitMQ - Symfony UK Meetup
Love and Loss: A Symfony Security Play
A high profile project with Symfony and API Platform: beIN SPORTS
Rich domain model with symfony 2.5 and doctrine 2.5
Présentation sur l'accessibilité numérique / Evènement université de Lille 3
Symfony Guard Authentication: Fun with API Token, Social Login, JWT and more
30 Symfony Best Practices
Symfony in microservice architecture
Creating hypermedia APIs in a few minutes using the API Platform framework
Symfony: Your Next Microframework (SymfonyCon 2015)
New Symfony Tips & Tricks (SymfonyCon Paris 2015)
Single-Page-Application & REST security
Symfony tips and tricks

Similar to Service approach for development REST API in Symfony2 (20)

PDF
The Naked Bundle - Symfony Barcelona
PDF
The Naked Bundle - Symfony Usergroup Belgium
PDF
The Naked Bundle - Tryout
PDF
The Naked Bundle - Symfony Live London 2014
ODP
Symfony2, creare bundle e valore per il cliente
PDF
Rest in practice con Symfony2
PDF
How I started to love design patterns
PDF
Desymfony 2011 - Habemus Bundles
PDF
Framework agnostic application Will it fit with Symfony? - Symfony live warsa...
KEY
次世代PHPフレームワーク Symfony2
PDF
Migrare da symfony 1 a Symfony2
PDF
How I started to love design patterns
PDF
Symfony 2 (PHP Quebec 2009)
PDF
Symfony2 - from the trenches
PPTX
Speed up your developments with Symfony2
PDF
Build powerfull and smart web applications with Symfony2
PDF
symfony on action - WebTech 207
PDF
How Kris Writes Symfony Apps
PDF
Some tips to improve developer experience with Symfony
PPTX
Symfony2 your way
The Naked Bundle - Symfony Barcelona
The Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Tryout
The Naked Bundle - Symfony Live London 2014
Symfony2, creare bundle e valore per il cliente
Rest in practice con Symfony2
How I started to love design patterns
Desymfony 2011 - Habemus Bundles
Framework agnostic application Will it fit with Symfony? - Symfony live warsa...
次世代PHPフレームワーク Symfony2
Migrare da symfony 1 a Symfony2
How I started to love design patterns
Symfony 2 (PHP Quebec 2009)
Symfony2 - from the trenches
Speed up your developments with Symfony2
Build powerfull and smart web applications with Symfony2
symfony on action - WebTech 207
How Kris Writes Symfony Apps
Some tips to improve developer experience with Symfony
Symfony2 your way

More from Sumy PHP User Grpoup (6)

PDF
PDF
Using Elastic Search Outside Full-Text Search
PPTX
Путешествия во времени
PPTX
High Availability в жизни обычного разработчика
PPTX
Php micro frameworks
PPTX
Oro open source solutions
Using Elastic Search Outside Full-Text Search
Путешествия во времени
High Availability в жизни обычного разработчика
Php micro frameworks
Oro open source solutions

Recently uploaded (20)

PPTX
UNIT II: Software design, software .pptx
PPTX
ROI from Efficient Content & Campaign Management in the Digital Media Industry
PPTX
FLIGHT TICKET API | API INTEGRATION PLATFORM
PPTX
Human Computer Interaction lecture Chapter 2.pptx
PDF
Sanket Mhaiskar Resume - Senior Software Engineer (Backend, AI)
PPTX
Streamlining Project Management in the AV Industry with D-Tools for Zoho CRM ...
PDF
Adlice Diag Crack With Serial Key Free Download 2025
PPT
3.Software Design for software engineering
PDF
Odoo Construction Management System by CandidRoot
PPTX
AI Tools Revolutionizing Software Development Workflows
PDF
Ragic Data Security Overview: Certifications, Compliance, and Network Safegua...
PDF
SOFTWARE ENGINEERING Software Engineering (3rd Edition) by K.K. Aggarwal & Yo...
PPTX
Independent Consultants’ Biggest Challenges in ERP Projects – and How Apagen ...
PDF
Mobile App for Guard Tour and Reporting.pdf
PDF
Top AI Tools for Project Managers: My 2025 AI Stack
PPTX
Foundations of Marketo Engage: Nurturing
PPTX
Chapter_05_System Modeling for software engineering
PDF
Building an Inclusive Web Accessibility Made Simple with Accessibility Analyzer
PPTX
Bandicam Screen Recorder 8.2.1 Build 2529 Crack
PDF
How to Set Realistic Project Milestones and Deadlines
UNIT II: Software design, software .pptx
ROI from Efficient Content & Campaign Management in the Digital Media Industry
FLIGHT TICKET API | API INTEGRATION PLATFORM
Human Computer Interaction lecture Chapter 2.pptx
Sanket Mhaiskar Resume - Senior Software Engineer (Backend, AI)
Streamlining Project Management in the AV Industry with D-Tools for Zoho CRM ...
Adlice Diag Crack With Serial Key Free Download 2025
3.Software Design for software engineering
Odoo Construction Management System by CandidRoot
AI Tools Revolutionizing Software Development Workflows
Ragic Data Security Overview: Certifications, Compliance, and Network Safegua...
SOFTWARE ENGINEERING Software Engineering (3rd Edition) by K.K. Aggarwal & Yo...
Independent Consultants’ Biggest Challenges in ERP Projects – and How Apagen ...
Mobile App for Guard Tour and Reporting.pdf
Top AI Tools for Project Managers: My 2025 AI Stack
Foundations of Marketo Engage: Nurturing
Chapter_05_System Modeling for software engineering
Building an Inclusive Web Accessibility Made Simple with Accessibility Analyzer
Bandicam Screen Recorder 8.2.1 Build 2529 Crack
How to Set Realistic Project Milestones and Deadlines

Service approach for development REST API in Symfony2