SlideShare a Scribd company logo
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
Ad

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
Ad

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

PDF
Doctrine For Beginners
PPTX
Magento Live Australia 2016: Request Flow
PDF
How kris-writes-symfony-apps-london
PPT
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
PDF
Symfony internals [english]
PDF
Silex Cheat Sheet
PDF
Silex Cheat Sheet
PDF
How Kris Writes Symfony Apps
PDF
Desymfony 2011 - Habemus Bundles
PDF
I Phone On Rails
PDF
Unit testing after Zend Framework 1.8
PDF
TYPO3 Flow 2.0 (T3CON13 San Francisco)
PDF
Symfony tips and tricks
PDF
Symfony2 for Midgard Developers
PDF
feature flagging with rails engines v0.2
PDF
関西PHP勉強会 php5.4つまみぐい
PDF
WordPress REST API hacking
PDF
Complex Sites with Silex
ODP
CodeIgniter PHP MVC Framework
PPT
Redmine Betabeers SVQ
Doctrine For Beginners
Magento Live Australia 2016: Request Flow
How kris-writes-symfony-apps-london
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
Symfony internals [english]
Silex Cheat Sheet
Silex Cheat Sheet
How Kris Writes Symfony Apps
Desymfony 2011 - Habemus Bundles
I Phone On Rails
Unit testing after Zend Framework 1.8
TYPO3 Flow 2.0 (T3CON13 San Francisco)
Symfony tips and tricks
Symfony2 for Midgard Developers
feature flagging with rails engines v0.2
関西PHP勉強会 php5.4つまみぐい
WordPress REST API hacking
Complex Sites with Silex
CodeIgniter PHP MVC Framework
Redmine Betabeers SVQ

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)

PDF
Understanding Forklifts - TECH EHS Solution
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PPTX
ai tools demonstartion for schools and inter college
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PPTX
Transform Your Business with a Software ERP System
PPTX
Online Work Permit System for Fast Permit Processing
PDF
top salesforce developer skills in 2025.pdf
PDF
System and Network Administration Chapter 2
PPTX
Operating system designcfffgfgggggggvggggggggg
PPT
Introduction Database Management System for Course Database
PDF
Softaken Excel to vCard Converter Software.pdf
PPTX
Odoo POS Development Services by CandidRoot Solutions
PPTX
CHAPTER 2 - PM Management and IT Context
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Understanding Forklifts - TECH EHS Solution
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Which alternative to Crystal Reports is best for small or large businesses.pdf
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Adobe Illustrator 28.6 Crack My Vision of Vector Design
ai tools demonstartion for schools and inter college
Design an Analysis of Algorithms II-SECS-1021-03
2025 Textile ERP Trends: SAP, Odoo & Oracle
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Transform Your Business with a Software ERP System
Online Work Permit System for Fast Permit Processing
top salesforce developer skills in 2025.pdf
System and Network Administration Chapter 2
Operating system designcfffgfgggggggvggggggggg
Introduction Database Management System for Course Database
Softaken Excel to vCard Converter Software.pdf
Odoo POS Development Services by CandidRoot Solutions
CHAPTER 2 - PM Management and IT Context
VVF-Customer-Presentation2025-Ver1.9.pptx
Lecture 3: Operating Systems Introduction to Computer Hardware Systems

Service approach for development REST API in Symfony2