Slide 1

Slide 1 text

Build Restful API easily with Symfony Sarah Khalil - January 29th, 2016

Slide 2

Slide 2 text

Who am I? • Head of • Trainer & Developer • Enjoying sharer Sarah Khalil @saro0h

Slide 3

Slide 3 text

No content

Slide 4

Slide 4 text

What’s the plan?

Slide 5

Slide 5 text

What’s the plan? Back to basics 1

Slide 6

Slide 6 text

What’s the plan? Back to basics 1 How to do it? 2

Slide 7

Slide 7 text

What’s the plan? Back to basics 1 Alternative tools 3 How to do it? 2

Slide 8

Slide 8 text

What is REST?

Slide 9

Slide 9 text

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

Slide 10

Slide 10 text

No content

Slide 11

Slide 11 text

No content

Slide 12

Slide 12 text

No content

Slide 13

Slide 13 text

No content

Slide 14

Slide 14 text

The 6 constraints of REST

Slide 15

Slide 15 text

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

Slide 16

Slide 16 text

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

Slide 17

Slide 17 text

Cacheable (3/6) Avoid useless requests

Slide 18

Slide 18 text

Layered system (4/6) The client doesn’t know the system behind

Slide 19

Slide 19 text

Uniform interface (5/6) Each resource has its identifier: the URI. Each resource has its representation. Auto-descripted message: for instance, JSON = content-type header.

Slide 20

Slide 20 text

Code on demand (6/6) The client download some code and executes it The server is not aware of what is happening anymore optional

Slide 21

Slide 21 text

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

Slide 22

Slide 22 text

Restful API

Slide 23

Slide 23 text

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

Slide 24

Slide 24 text

http://martinfowler.com

Slide 25

Slide 25 text

HATEOAS Hypermedia as the engine of Application State Discoverability => Links!

Slide 26

Slide 26 text

No content

Slide 27

Slide 27 text

Symfony Full Stack JMSSerializerBundle FOSRestBundle BazingaHateoasBundle NelmioApiDocBundle

Slide 28

Slide 28 text

Symfony Full Stack JMSSerializerBundle FOSRestBundle BazingaHateoasBundle NelmioApiDocBundle

Slide 29

Slide 29 text

Symfony Full Stack JMSSerializerBundle FOSRestBundle BazingaHateoasBundle NelmioApiDocBundle

Slide 30

Slide 30 text

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

Slide 31

Slide 31 text

Response HTTP/1.1 200 OK Host: 127.0.0.1:8000 Content-Type: text/html; charset=UTF-8

Slide 32

Slide 32 text

Symfony\Component\HttpFoundation\Request Symfony\Component\HttpFoundation\Response

Slide 33

Slide 33 text

HttpKernel

Slide 34

Slide 34 text

Symfony Full Stack JMSSerializerBundle FOSRestBundle BazingaHateoasBundle NelmioApiDocBundle

Slide 35

Slide 35 text

Symfony Full Stack JMSSerializerBundle FOSRestBundle BazingaHateoasBundle NelmioApiDocBundle Work with resources

Slide 36

Slide 36 text

No content

Slide 37

Slide 37 text

Json/XML Object serialization deserialization

Slide 38

Slide 38 text

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

Slide 39

Slide 39 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 40

Slide 40 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 41

Slide 41 text

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

Slide 42

Slide 42 text

Serializer handler Specific needs Implements JMS\Serializer\Handler\SubscribingHandlerInterface

Slide 43

Slide 43 text

No content

Slide 44

Slide 44 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 45

Slide 45 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 46

Slide 46 text

Events

Slide 47

Slide 47 text

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

Slide 48

Slide 48 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 49

Slide 49 text

Event subscriber

Slide 50

Slide 50 text

Other features Serialization group Versionning

Slide 51

Slide 51 text

No content

Slide 52

Slide 52 text

Symfony Full Stack JMSSerializerBundle FOSRestBundle BazingaHateoasBundle NelmioApiDocBundle

Slide 53

Slide 53 text

Symfony Full Stack JMSSerializerBundle FOSRestBundle BazingaHateoasBundle NelmioApiDocBundle Setup your Symfony application

Slide 54

Slide 54 text

No content

Slide 55

Slide 55 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 56

Slide 56 text

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

Slide 57

Slide 57 text

Content-Type negociation 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 58

Slide 58 text

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

Slide 59

Slide 59 text

Validation

Slide 60

Slide 60 text

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

Slide 61

Slide 61 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 62

Slide 62 text

Param Fetcher

Slide 63

Slide 63 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 64

Slide 64 text

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

Slide 65

Slide 65 text

Error handling

Slide 66

Slide 66 text

Error handling Option 1 fos_rest: codes: 'Symfony\Component\Routing\Exception\ResourceNotFoundException': 404 'Doctrine\ORM\OptimisticLockException': HTTP_CONFLICT

Slide 67

Slide 67 text

fos_rest: view: exception_wrapper_handler: My\Bundle\Handler\MyExceptionWrapperHandler 1 Error handling Option 2

Slide 68

Slide 68 text

fos_rest: view: exception_wrapper_handler: My\Bundle\Handler\MyExceptionWrapperHandler 1 implements FOS\RestBundle\ViewExceptionWrapperHandlerInterface 2 Error handling Option 2

Slide 69

Slide 69 text

fos_rest: view: exception_wrapper_handler: My\Bundle\Handler\MyExceptionWrapperHandler 1 implements FOS\RestBundle\ViewExceptionWrapperHandlerInterface 2 public function wrap($data) { return new MyExceptionWrapper($data); } 3 Error handling Option 2

Slide 70

Slide 70 text

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

Slide 71

Slide 71 text

Other features • Automatic generation of routes • Consistency • Versioning • url • mime type And way more! http://symfony.com/doc/master/bundles/FOSRestBundle/index.html

Slide 72

Slide 72 text

Symfony Full Stack JMSSerializerBundle FOSRestBundle BazingaHateoasBundle NelmioApiDocBundle

Slide 73

Slide 73 text

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

Slide 74

Slide 74 text

No content

Slide 75

Slide 75 text

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

Slide 76

Slide 76 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 77

Slide 77 text

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

Slide 78

Slide 78 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 Expression Language

Slide 79

Slide 79 text

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

Slide 80

Slide 80 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 81

Slide 81 text

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

Slide 82

Slide 82 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 83

Slide 83 text

class CollectionRepresentation { private $resources; public function __construct($resources) { $this->resources = $resources; } public function getResources() { return $this->resources; } }

Slide 84

Slide 84 text

"resources": { { "name": « Mercure Los Angeles" }, { "name": "Novotel Mexico" }, }

Slide 85

Slide 85 text

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

Slide 86

Slide 86 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 87

Slide 87 text

Symfony Full Stack JMSSerializerBundle FOSRestBundle BazingaHateoasBundle NelmioApiDocBundle Guzzle

Slide 88

Slide 88 text

Symfony Full Stack JMSSerializerBundle FOSRestBundle BazingaHateoasBundle NelmioApiDocBundle Guzzle Communicate between microservices

Slide 89

Slide 89 text

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

Slide 90

Slide 90 text

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

Slide 91

Slide 91 text

No content

Slide 92

Slide 92 text

No content

Slide 93

Slide 93 text

Security

Slide 94

Slide 94 text

Symfony Full Stack JMSSerializerBundle FOSRestBundle BazingaHateoasBundle NelmioApiDocBundle

Slide 95

Slide 95 text

Authentication & Authorization

Slide 96

Slide 96 text

Authentication & Authorization

Slide 97

Slide 97 text

Authentication & Authorization

Slide 98

Slide 98 text

Authentication with multiple API’s

Slide 99

Slide 99 text

Service 1 Service 2 Client Frontend 2 Frontend 1 Service 3 Service 4

Slide 100

Slide 100 text

No content

Slide 101

Slide 101 text

Workflow 1. The user authenticates [him|her]self on frontend 1 2. Do some stuff 3. Then clicks on a link that brings him/ her to the frontend 2

Slide 102

Slide 102 text

Service 1 Service 2 Client Frontend 2 Frontend 1 Service 3 Service 4 GET /admin HTTP/1.1 User-Agent: curl/7.37.1 Host: 127.0.0.1:8000 Accept: */* Authorization: Bearer XXXXXX

Slide 103

Slide 103 text

Get the token In an authenticator, grab the Authorization header value

Slide 104

Slide 104 text

Get the token public function createToken(Request $request, $providerKey) { $bearer = $request->headers… }

Slide 105

Slide 105 text

Validate a token / Get a new one…

Slide 106

Slide 106 text

No content

Slide 107

Slide 107 text

No content

Slide 108

Slide 108 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 109

Slide 109 text

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

Slide 110

Slide 110 text

FosHttpCacheBundle Keep it mind

Slide 111

Slide 111 text

No content

Slide 112

Slide 112 text

Ease the usage of your API

Slide 113

Slide 113 text

Symfony Full Stack JMSSerializerBundle FOSRestBundle BazingaHateoasBundle NelmioApiDocBundle

Slide 114

Slide 114 text

Symfony Full Stack JMSSerializerBundle FOSRestBundle BazingaHateoasBundle NelmioApiDocBundle Documentation

Slide 115

Slide 115 text

No content

Slide 116

Slide 116 text

No content

Slide 117

Slide 117 text

Alternative to FOSRestBundle

Slide 118

Slide 118 text

https://api-platform.com/

Slide 119

Slide 119 text

No content

Slide 120

Slide 120 text

No content

Slide 121

Slide 121 text

http://tinyurl.com/sfliveparis

Slide 122

Slide 122 text

Thank you! @saro0h speakerdeck.com/saro0h/ github.com/saro0h/oauth-github Follow me on @catlannister Come see us at the SensioLabs booth!