Slide 1

Slide 1 text

Build Restful API easily with Symfony Sarah Khalil - October 21st, 2015

Slide 2

Slide 2 text

Who I am? • Head of • Trainer & Developer • Enjoying sharer • Contributor to

Slide 3

Slide 3 text

No content

Slide 4

Slide 4 text

What is REST?

Slide 5

Slide 5 text

What is REST? • REpresentational State Transfer • Architecture (not a protocol!) • Associated to Service Oriented Architecture • Management of resources

Slide 6

Slide 6 text

The 6 constraints of REST

Slide 7

Slide 7 text

Client - Server (1/6) • Separation of concerns. • Portability.

Slide 8

Slide 8 text

Stateless (2/6) • Based on HTTP. • Session has to be held on the client side.

Slide 9

Slide 9 text

Cacheable (3/6) • Avoid useless requests.

Slide 10

Slide 10 text

Layered system (4/6) • The client requests a resource but it doesn’t know the system behind.

Slide 11

Slide 11 text

Uniform interface (5/6) • Each resource has its identified: the URI. • Each resource has its representation. • Auto-descripted message: if it’s JSON, the HTTP response has a content-type header saying.

Slide 12

Slide 12 text

Code on demand (6/6) • The client should be executing some code coming from the server, to avoid more work on the server side.

Slide 13

Slide 13 text

HTTP Methods • GET • POST • PUT • PATCH • DELETE • OPTIONS • CONNECT • HEAD

Slide 14

Slide 14 text

Restful API

Slide 15

Slide 15 text

Keep’em in mind • JSON, XML, HTML… • By developers and for developers • Scalability • Latency • Security !

Slide 16

Slide 16 text

http://martinfowler.com

Slide 17

Slide 17 text

HATEOAS • Hypermedia as the engine of Application State • Discoverability

Slide 18

Slide 18 text

No content

Slide 19

Slide 19 text

Symfony Full Stack JMSSerializerBundle FOSRestBundle BazingaHateoasBundle NelmioApiDocBundle

Slide 20

Slide 20 text

Symfony Full Stack JMSSerializerBundle FOSRestBundle BazingaHateoasBundle NelmioApiDocBundle

Slide 21

Slide 21 text

Symfony Full Stack JMSSerializerBundle FOSRestBundle BazingaHateoasBundle NelmioApiDocBundle

Slide 22

Slide 22 text

Philosophy

Slide 23

Slide 23 text

Request GET /users HTTP/1.1 User-Agent: curl/7.37.1 Host: 127.0.0.1:8000 Accept: */*

Slide 24

Slide 24 text

Symfony\Component\HttpFoundation\Request

Slide 25

Slide 25 text

Response HTTP/1.1 200 OK Host: 127.0.0.1:8000 Connection: close X-Powered-By: PHP/5.6.3 Set-Cookie: PHPSESSID=ecdadm6o2d5v9ei0m181j8gh96; path=/ Cache-Control: no-cacheDate: Wed, 11 Feb 2015 23:42:50 GMT Content-Type: text/html; charset=UTF-8 X-Debug-Token: 32860d X-Debug-Token-Link: /_profiler/32860d

Slide 26

Slide 26 text

Symfony\Component\HttpFoundation \Response

Slide 27

Slide 27 text

HttpKernel

Slide 28

Slide 28 text

Symfony Full Stack JMSSerializerBundle FOSRestBundle BazingaHateoasBundle NelmioApiDocBundle

Slide 29

Slide 29 text

Symfony Full Stack JMSSerializerBundle FOSRestBundle BazingaHateoasBundle NelmioApiDocBundle Work with resources

Slide 30

Slide 30 text

No content

Slide 31

Slide 31 text

Json/XML Object serialization deserialization

Slide 32

Slide 32 text

Configuration • XML, YML and Annotation. • http://jmsyst.com/libs/serializer/master/reference • Helper to serialize properties the way you need.

Slide 33

Slide 33 text

class DefaultController { public function indexAction() { $obj = new \StdClass(); $obj->latitude = -33.87087; $obj->longitude = 151.225459; $data = $this->get(‘jms_serializer’) ->serialize($obj, ’json’); return new Response( $data, 200, array(‘Content-Type’=>’application/json’) ); } }

Slide 34

Slide 34 text

HTTP/1.1 200 OK Host: 127.0.0.1 X-Powered-By: PHP/5.6.3 Content-Type: application/json { "latitude": -33.87087, "longitude": 151.225459 } Output

Slide 35

Slide 35 text

Exclusion policy /** * @JMS\ExclusionPolicy("all") */ class Product { /** * @JMS\Expose() */ private $name; private $users; } • Visitor pattern • Object graph • Relations (xToMany)

Slide 36

Slide 36 text

Serializer handler • Specific needs • implements JMS\Serializer\Handler\SubscribingHandlerInterface •

Slide 37

Slide 37 text

public static function getSubscribingMethods() { return [ [ 'direction' => GraphNavigator::DIRECTION_SERIALIZATION, 'format' => ‘json', 'type' => ‘AppBundle\MyClass’, 'method' => ‘serialize', ], [ 'direction' => GraphNavigator::DIRECTION_DESERIALIZATION, 'format' => ‘json', 'type' => ‘AppBundle\MyClass', 'method' => ‘deserialize', ], ]; }

Slide 38

Slide 38 text

public function serialize( JsonSerializationVisitor $visitor, MyClass $object, array $type, Context $context ) { $data = $object->toArray(); return $data; } public function deserialize(JsonDeserializationVisitor $visitor, $data) { $object = new AppBundle\MyClass($data); return $object; }

Slide 39

Slide 39 text

Event subscriber • http://jmsyst.com/libs/serializer/master/event_system • implements JMS\Serializer\EventDispatcher\EventSubscriberInterface

Slide 40

Slide 40 text

serialization deserialization

Slide 41

Slide 41 text

Object serialization deserialization

Slide 42

Slide 42 text

Object serialization deserialization serializer.pre_serialize

Slide 43

Slide 43 text

Object serialization deserialization serializer.pre_serialize

Slide 44

Slide 44 text

Object serialization deserialization serializer.pre_serialize serializer.post_serialize

Slide 45

Slide 45 text

Json/XML Object serialization deserialization serializer.pre_serialize serializer.post_serialize

Slide 46

Slide 46 text

Json/XML Object serialization deserialization serializer.pre_serialize serializer.post_serialize serializer.pre_deserialize

Slide 47

Slide 47 text

Json/XML Object serialization deserialization serializer.pre_serialize serializer.post_serialize serializer.pre_deserialize

Slide 48

Slide 48 text

Json/XML Object serialization deserialization serializer.pre_serialize serializer.post_serialize serializer.pre_deserialize serializer.post_deserialize

Slide 49

Slide 49 text

class PostSerializeMediaListener implements EventSubscriberInterface { public function onPostSerialize(ObjectEvent $event) { $myObject = $event->getObject(); $event->getVisitor()->addData('newElementInJson', 'information’); } public static function getSubscribedEvents() { return array( array( 'event' => Events::POST_SERIALIZE, 'format' => ‘json', 'class' => ‘AppBundle\MyClass', 'method' => ‘onPostSerialize', ), ); } }

Slide 50

Slide 50 text

Other features • Serialization group • Versionning

Slide 51

Slide 51 text

Symfony Full Stack JMSSerializerBundle FOSRestBundle BazingaHateoasBundle NelmioApiDocBundle

Slide 52

Slide 52 text

Symfony Full Stack JMSSerializerBundle FOSRestBundle BazingaHateoasBundle NelmioApiDocBundle Setup your Symfony application

Slide 53

Slide 53 text

No content

Slide 54

Slide 54 text

Controller # app/config/config.yml fos_rest: view: view_response_listener: force sensio_framework_extra: view: { annotations: false } /** * @View() */ public function getUsersAction() { … return $data; }

Slide 55

Slide 55 text

Content-Type negociation • Request => Accept • priorities of media-type(s) that your application is ready to get. • Response => Content-Type • the media type of the response (html, json, png…).

Slide 56

Slide 56 text

Content-Type negociation • Priorities define the order of media types as the application prefers: • Request: Accept text/json;q=0.9,*/*;q=0.8,text/html # app/config/config.yml fos_rest: format_listener: rules: - { path: '^/', priorities: ['json'], fallback_format: html } weighting

Slide 57

Slide 57 text

Request body converter • Decoder • ParamConverter # app/config/config.yml sensio_framework_extra: request: { converters: true } fos_rest: body_converter: enabled: true /** * @ParamConverter("post", converter="fos_rest.request_body") */ public function updateAction(Post $post) { }

Slide 58

Slide 58 text

Validation

Slide 59

Slide 59 text

Validation (with the Symfony Validator component) Configuration fos_rest: body_converter: enabled: true validate: true validation_errors_argument: validationErrors

Slide 60

Slide 60 text

Validation (with the Symfony Validator component) Usage /** * @ParamConverter("post", converter="fos_rest.request_body") */ public function putPostAction(Post $post, ConstraintViolationListInterface $validationErrors) { if (count($validationErrors) > 0) { // Handle validation errors } }

Slide 61

Slide 61 text

Param Fetcher

Slide 62

Slide 62 text

/** * @QueryParam( * name="sort", * requirements="(asc|desc)", * allowBlank=false, * default="asc", * description="Sort direction" * ) * @RequestParam( * name="firstname", * requirements="[a-z]+" * ) * @QueryParam( * array=true, * name="filters", * requirements=@MyComplexConstraint * ) */ public function getArticlesAction(ParamFetcher $paramFetcher) {} http://mydomain.com/resources?sort=desc In $request->request ($_POST) fos_rest.param_fetcher_listener: true

Slide 63

Slide 63 text

/** * @QueryParam(name="page", requirements="\d+", default="1") */ public function getArticlesAction($page) {} fos_rest.param_fetcher_listener: force

Slide 64

Slide 64 text

Error handling

Slide 65

Slide 65 text

Error handling (1/2) fos_rest: codes: 'Symfony\Component\Routing\Exception\ResourceNotFoundException': 404 'Doctrine\ORM\OptimisticLockException': HTTP_CONFLICT

Slide 66

Slide 66 text

Error handling (2/2) fos_rest: view: exception_wrapper_handler: My\Bundle\Handler\MyExceptionWrapperHandler implements FOS\RestBundle\ViewExceptionWrapperHandlerInterface public function wrap($data) { return new MyExceptionWrapper($data); } Take exemple on FOS\RestBundle\Util\ExceptionWrapper

Slide 67

Slide 67 text

Other features • Automatic generation of routes • Consistency • Versioning • url • mime type • Take a look at the documentation • http://symfony.com/doc/master/bundles/FOSRestBundle/index.html

Slide 68

Slide 68 text

Symfony Full Stack JMSSerializerBundle FOSRestBundle BazingaHateoasBundle NelmioApiDocBundle

Slide 69

Slide 69 text

Symfony Full Stack JMSSerializerBundle FOSRestBundle BazingaHateoasBundle NelmioApiDocBundle Unlock the level 3 of the Richardson’s model

Slide 70

Slide 70 text

No content

Slide 71

Slide 71 text

HAL • Hypertext Application Language • _links - relations • _embedded - related resource(s) • self • Specifications: http://stateless.co/hal_specification.html

Slide 72

Slide 72 text

JSON API • Similar to HAL • meta - meta info such as pagination… • links - Relations (xToOne - xToMany) • linked - Resource(s) linked • Specifications : http://jsonapi.org/format/

Slide 73

Slide 73 text

Configuration • Annotation, XML and YML • Relies on Expression Language (since Symfony 2.4)

Slide 74

Slide 74 text

/** * @Hateoas\Relation( * "self", * href = @Hateoas\Route( * "get_notification", * absolute= true, * parameters = { * "id" = "expr(object.getId())", * "user" = "expr(service(‘security.context’).getToken().getUser().getUuid())" * } * ) * ) */ class Notification

Slide 75

Slide 75 text

Result { "id": 1, "_links": { "self": { "href": "http://domaine.name/users/eh1754329986/notifications/1/" } } }

Slide 76

Slide 76 text

/** * … * @Hateoas\Relation( * "activity", * href = "expr(‘/activity/'~object.getActivity().getId()", * embedded = "expr(object.getActivity())", * exclusion = @Hateoas\Exclusion(excludeIf = "expr(object.getActivity() === null)") * ) */ class Notification

Slide 77

Slide 77 text

Result { "id": 1, "_embedded": { "activity": { "id": 3, "content": "Activity content", "_links": { "self": { "href": "/activities/3" } } } } }

Slide 78

Slide 78 text

Representation • Use representation to decorate your resource • Hateoas\Representation\PaginatedRepresentation • And many more: https://github.com/willdurand/Hateoas/tree/master/src/Hateoas/Representation

Slide 79

Slide 79 text

"page": 1, "limit": 10, "pages": "100", "total": 1000, "_links": { "self": { "href": "http://domain.name/notifcations?page=1&limit=10" }, "first": { "href": "http://domain.name/notifcations?page=1&limit=1" }, "last": { "href": "http://domain.name/notifcations?page=100&limit=1" }, "next": { "href": "http://domain.name/notifcations?page=2&limit=1" } }

Slide 80

Slide 80 text

Representation • Any representation you need ! • A class with the properties you need. • Let the serializer do its job.

Slide 81

Slide 81 text

Symfony Full Stack JMSSerializerBundle FOSRestBundle BazingaHateoasBundle NelmioApiDocBundle Guzzle

Slide 82

Slide 82 text

Symfony Full Stack JMSSerializerBundle FOSRestBundle BazingaHateoasBundle NelmioApiDocBundle Guzzle Communicate between micro services

Slide 83

Slide 83 text

Frontend Service 1 Service 2 Service 3 Service 4 Private network Client

Slide 84

Slide 84 text

Guzzle Bundle • HTTP Client • Request • Response • HTTPS • Error management • https://github.com/misd- service-development/guzzle- bundle • https://github.com/csarrazi/ CsaGuzzleBundle

Slide 85

Slide 85 text

No content

Slide 86

Slide 86 text

No content

Slide 87

Slide 87 text

Security

Slide 88

Slide 88 text

Symfony Full Stack JMSSerializerBundle FOSRestBundle BazingaHateoasBundle NelmioApiDocBundle

Slide 89

Slide 89 text

Authentication • Authorization header: Authorization: Bearer • https://github.com/poledev/katas/tree/kata- authentication • http://symfony.com/doc/current/cookbook/security/ api_key_authentication.html • Make it stateless!

Slide 90

Slide 90 text

Authorization • access_control • $this->get(‘security.authorization_checker’)->isGranted('ROLE_ADMIN') • {% if is_granted(‘ROLE_ADMIN’) %} • Voter • ACL • …

Slide 91

Slide 91 text

FosHttpCacheBundle Keep it mind

Slide 92

Slide 92 text

No content

Slide 93

Slide 93 text

One last thing

Slide 94

Slide 94 text

Symfony Full Stack JMSSerializerBundle FOSRestBundle BazingaHateoasBundle NelmioApiDocBundle

Slide 95

Slide 95 text

Symfony Full Stack JMSSerializerBundle FOSRestBundle BazingaHateoasBundle NelmioApiDocBundle Documentation

Slide 96

Slide 96 text

No content

Slide 97

Slide 97 text

No content

Slide 98

Slide 98 text

Oh I forgot to introduce you Lannister! @catlannister

Slide 99

Slide 99 text

http://tinyurl.com/sfcon2015

Slide 100

Slide 100 text

http://tinyurl.com/sfliveusa

Slide 101

Slide 101 text

Thank you! @saro0h speakerdeck.com/saro0h/ saro0h This is a zero guys!