Slide 1

Slide 1 text

www.galvao.eti.br CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 1 / 44 Desenvolvendo APIs com PHP & Expressive ElePHPant by Vincent Pontier. & Expressive APIs com HTTP/1.1 200 OK php

Slide 2

Slide 2 text

Presidente (2012 – 2017) da ABRAPHP – Associação Brasileira de Profissionais PHP Diretor da PHP Conference Brasil Evangelista e Contribuidor para a Linguagem Evangelista Laminas Project Embaixador Fedora LATAM Professor Convidado (Especialista) de Pós-Graduação (PR e SC) 25+ anos desenvolvendo sistemas e aplicações com interface web 20+ destes com PHP 12+ com Zend Framework Palestrante em eventos nacionais e internacionais Professor de cursos presenciais e a distância Quem?! CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 2 / 44 www.galvao.eti.br www.galvao.eti.br Desenvolvendo APIs com PHP & Expressive

Slide 3

Slide 3 text

Objetivo CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 3 / 44 www.galvao.eti.br Expor detalhes envolvidos na criação de uma API Web e demonstrar a criação de um exemplo utilizando PHP7 e Expressive1. [1] https://www.galvao.eti.br/do-zend-framework-ao-laminas/ Desenvolvendo APIs com PHP & Expressive

Slide 4

Slide 4 text

API Web? CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 4 / 44 www.galvao.eti.br Application Programming Interface Desenvolvendo APIs com PHP & Expressive

Slide 5

Slide 5 text

API Web? CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 5 / 44 www.galvao.eti.br Application Programming Interface para a web, ou seja: Desenvolvendo APIs com PHP & Expressive

Slide 6

Slide 6 text

API Web? CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 6 / 44 www.galvao.eti.br Application Programming Interface Recurso http[s]:// Endereço Dados Método [ ] para a web, ou seja: Desenvolvendo APIs com PHP & Expressive

Slide 7

Slide 7 text

API Web? CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 7 / 44 www.galvao.eti.br “Mas isso é simplesmente a Web!” Desenvolvendo APIs com PHP & Expressive

Slide 8

Slide 8 text

API Web? CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 8 / 44 www.galvao.eti.br “Mas isso é simplesmente a Web!” Sim ... e não. Desenvolvendo APIs com PHP & Expressive

Slide 9

Slide 9 text

API Web? CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 9 / 44 www.galvao.eti.br “Mas isso é simplesmente a Web!” Sim ... e não. APIs Web: Desenvolvendo APIs com PHP & Expressive

Slide 10

Slide 10 text

API Web? CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 10 / 44 www.galvao.eti.br “Mas isso é simplesmente a Web!” Sim ... e não. APIs Web: São não-interativas* Desenvolvendo APIs com PHP & Expressive

Slide 11

Slide 11 text

API Web? CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 11 / 44 www.galvao.eti.br “Mas isso é simplesmente a Web!” Sim ... e não. APIs Web: São não-interativas* Retornam dados, sem apresentação Desenvolvendo APIs com PHP & Expressive

Slide 12

Slide 12 text

Anatomia CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 12 / 44 www.galvao.eti.br Desenvolvendo APIs com PHP & Expressive

Slide 13

Slide 13 text

Duas Validações?! CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 13 / 44 www.galvao.eti.br 1ª Validação: Vale a pena processar esta Requisição? 2ª Validação: Resultado do processamento Desenvolvendo APIs com PHP & Expressive

Slide 14

Slide 14 text

Anatomia – PSR CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 14 / 44 www.galvao.eti.br 1ª Validação Processamento / 2ª Validação Desenvolvendo APIs com PHP & Expressive

Slide 15

Slide 15 text

FFUC – Frequently F ed Up Concepts CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 15 / 44 www.galvao.eti.br *** NÃO existe requisição sem identificação Desenvolvendo APIs com PHP & Expressive

Slide 16

Slide 16 text

FFUC – Frequently F ed Up Concepts CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 16 / 44 www.galvao.eti.br *** NÃO existe requisição sem identificação Evite usar Status Codes 5xx! Desenvolvendo APIs com PHP & Expressive

Slide 17

Slide 17 text

FFUC – Frequently F ed Up Concepts CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 17 / 44 www.galvao.eti.br *** NÃO existe requisição sem identificação Sucessos NEM SEMPRE geram Status 200 Evite usar Status Codes 5xx! Desenvolvendo APIs com PHP & Expressive

Slide 18

Slide 18 text

FFUC – Frequently F ed Up Concepts CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 18 / 44 www.galvao.eti.br *** NÃO existe requisição sem identificação Sucessos NEM SEMPRE geram Status 200 Erros NUNCA geram Status 200 Evite usar Status Codes 5xx! Desenvolvendo APIs com PHP & Expressive

Slide 19

Slide 19 text

FFUC – Frequently F ed Up Concepts CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 19 / 44 www.galvao.eti.br *** NÃO existe requisição sem identificação Sucessos NEM SEMPRE geram Status 200 Erros NUNCA geram Status 200 Erros NUNCA geram Status 200 Evite usar Status Codes 5xx! Desenvolvendo APIs com PHP & Expressive

Slide 20

Slide 20 text

FFUC – Frequently F ed Up Concepts CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 20 / 44 www.galvao.eti.br *** NÃO existe requisição sem identificação Sucessos NEM SEMPRE geram Status 200 Erros NUNCA geram Status 200 Erros NUNCA geram Status 200 Erros NUNCA geram Status 200 Evite usar Status Codes 5xx! Desenvolvendo APIs com PHP & Expressive

Slide 21

Slide 21 text

CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 21 / 44 www.galvao.eti.br Recurso criado? Processamento longo ou particionado? Sem contéudo na resposta? Outros casos 201 202* 204 200** Sucessos Desenvolvendo APIs com PHP & Expressive

Slide 22

Slide 22 text

CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 22 / 44 www.galvao.eti.br Recurso existe? Método Válido? Número de Requisições válido? Headers OK? Autenticação necessária, provida e válida? Usuário autorizado? Tamanho de Payload >= mínimo? Tamanho de Payload <= máximo? Payload válido? Conteúdo de resposta válido? 404 405 429 400* 401 403 400* 413 400* 406 1ª Validação 2ª Validação Erros Desenvolvendo APIs com PHP & Expressive

Slide 23

Slide 23 text

Recurso existe? Método Válido? Número de Requisições válido? Headers OK? Autenticação necessária, provida e válida? Usuário autorizado? Tamanho de Payload >= mínimo? Tamanho de Payload <= máximo? Payload válido? Conteúdo de resposta válido? 404 405 429 400* 401 403 400* 413 400* 406 1ª Validação 2ª Validação CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 23 / 44 www.galvao.eti.br Erros Fácil... Desenvolvendo APIs com PHP & Expressive

Slide 24

Slide 24 text

CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 24 / 44 www.galvao.eti.br … ou melhor ... Desenvolvendo APIs com PHP & Expressive

Slide 25

Slide 25 text

CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 25 / 44 www.galvao.eti.br … ou melhor ... Desenvolvendo APIs com PHP & Expressive

Slide 26

Slide 26 text

CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 26 / 44 www.galvao.eti.br … ou melhor ... https://github.com/galvao/Flow (WiP) Desenvolvendo APIs com PHP & Expressive

Slide 27

Slide 27 text

CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 27 / 44 www.galvao.eti.br Especificação Conceitualização Definição de Boas Práticas Documentação Ferramentas Geração (semi-)automatizada Desenvolvendo APIs com PHP & Expressive

Slide 28

Slide 28 text

CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 28 / 44 www.galvao.eti.br Use código-fonte que você não entende completamente e prepare-se para ser julgado DISCLAIMER Desenvolvendo APIs com PHP & Expressive

Slide 29

Slide 29 text

CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 29 / 44 www.galvao.eti.br Use código-fonte que você não entende completamente e prepare-se para ser julgado pelo Rei Koala do Inferno. DISCLAIMER Desenvolvendo APIs com PHP & Expressive

Slide 30

Slide 30 text

CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 30 / 44 www.galvao.eti.br openapi tags info version title contact name email paths /path método operationId summary tags responses status code description Especificação { "openapi": "3.0.2", "tags": [ { "name": "expressive" } ], "info": { "version": "1.0.0", "title": "Zend Expressive Demo", "contact": { "name": "Er Galvão Abbott", "email": "galvao@galvao.eti.br" } }, "paths": { "/test": { "get": { "operationId": "getTest", "summary": "Tests the demo", "tags": ["expressive", "demo"], "responses": { "200": { "description": "Test works" } } } } } } Desenvolvendo APIs com PHP & Expressive

Slide 31

Slide 31 text

CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 31 / 44 www.galvao.eti.br Documentação http://localhost:5000 speccy serve openapi.json Desenvolvendo APIs com PHP & Expressive

Slide 32

Slide 32 text

Skeleton CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 32 / 44 www.galvao.eti.br Inicialização da Skeleton e opções de instalação podem ser vistas em: https://asciinema.org/a/200553 composer create-project \ zendframework/zend-expressive-skeleton \ /var/www/html/zend-expressive-demo Desenvolvendo APIs com PHP & Expressive

Slide 33

Slide 33 text

Roteamento CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 33 / 44 www.galvao.eti.br Múltiplos Métodos Único Método $app->route(‘/test’, App\Handler\TestHandler::class, [‘POST’, ‘GET’], ‘test’ ); $app->get(‘/test’, App\Handler\TestHandler::class, ‘test’ ); Desenvolvendo APIs com PHP & Expressive

Slide 34

Slide 34 text

Roteamento CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 34 / 44 www.galvao.eti.br $app delete connect get head options patch post put trace route (‘/segmento-de-url’, middleware(s), ‘identificador’ ) (‘/segmento-de-url’, middleware(s), [método(s)], ‘identificador’ ) Desenvolvendo APIs com PHP & Expressive

Slide 35

Slide 35 text

CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 35 / 44 www.galvao.eti.br Handler 'Test success!', ], 200, [ 'X-Powered-By' => 'Expressive Awesomeness!', ]); } } Desenvolvendo APIs com PHP & Expressive

Slide 36

Slide 36 text

Respostas CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 36 / 44 www.galvao.eti.br return new Html Empty Json Redirect Text Response( ); ... * https://docs.zendframework.com/zend-diactoros/v2/custom-responses/#creating-custom-responses … e mais* Desenvolvendo APIs com PHP & Expressive

Slide 37

Slide 37 text

Testando CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 37 / 44 www.galvao.eti.br http --verbose --pretty all \ GET http://zend_expressive_demo/test GET /test HTTP/1.1 Accept: */* Accept-Encoding: gzip, deflate Connection: keep-alive Host: zend_expressive_demo User-Agent: HTTPie/0.9.4 HTTP/1.1 200 OK Connection: Keep-Alive Content-Type: application/json Date: Thu, 18 Oct 2018 15:24:15 GMT Keep-Alive: timeout=5, max=100 Server: Apache/2.4.34 (Fedora) Transfer-Encoding: chunked X-Powered-By: Expressive Awesomeness! { "details": "Test success!" } Desenvolvendo APIs com PHP & Expressive

Slide 38

Slide 38 text

CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 38 / 44 www.galvao.eti.br Adicionando Dados Configuração Injeção de Dependência Execução via Factory Desenvolvendo APIs com PHP & Expressive

Slide 39

Slide 39 text

CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 39 / 44 www.galvao.eti.br [ 'driver' => 'Pdo_Mysql', 'database' => 'expressive_demo', 'username' => 'usuario', 'password' => 'senha', ], ]; Configuração config/autoload/database.local.php Desenvolvendo APIs com PHP & Expressive

Slide 40

Slide 40 text

CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 40 / 44 www.galvao.eti.br [ 'aliases' => [ ], 'invokables' => [ ], 'factories' => [ DbAdapter::class => Zend\Db\Adapter\AdapterServiceFactory::class, App\Handler\TestHandler::class => App\Handler\TestHandlerFactory::class, ], ], ]; Injeção config/autoload/dependencies.global.php Desenvolvendo APIs com PHP & Expressive

Slide 41

Slide 41 text

CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 41 / 44 www.galvao.eti.br get(RouterInterface::class); $template = $container->has(TemplateRendererInterface::class) ? $container->get(TemplateRendererInterface::class) : null; return new TestHandler($router, $template, $container); } } Execução via Factory Desenvolvendo APIs com PHP & Expressive

Slide 42

Slide 42 text

CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 42 / 44 www.galvao.eti.br private $container; private $router; private $template; public function __construct( \Zend\Expressive\Router\ZendRouter $router, \Zend\Expressive\ZendView\ZendViewRenderer $template = null, \Psr\Container\ContainerInterface $container ) { $this->router = $router; $this->template = $template; $this->container = $container; } public function handle(ServerRequestInterface $request): ResponseInterface { $sql = new \Zend\Db\Sql\Sql($this->container->get('DbAdapter')); $select = $sql->select('foo'); $sth = $sql->prepareStatementForSqlObject($select); $result = $sth->execute(); return new JsonResponse([ 'details' => 'Test success!', 'result' => $result->current(), ], 200, [ 'X-Powered-By' => 'Expressive Awesomeness!', ]); } Execução via Factory Desenvolvendo APIs com PHP & Expressive

Slide 43

Slide 43 text

Links CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 43 / 44 www.galvao.eti.br Documentção Zend Expressive https://docs.zendframework.com/zend-expressive/v3/ Zend Diactoros https://docs.zendframework.com/zend-diactoros/ RFC 7231 #Status Codes https://tools.ietf.org/html/rfc7231#section-6 PSRs #7, 15, 17 e 18 https://www.php-fig.org/psr/ RTFM Ferramentas Swagger Editor Speccy HTTPie Postman jq Recursos APIs you won’t hate https://apisyouwonthate.com/ API Evangelist http://apievangelist.com/ Desenvolvendo APIs com PHP & Expressive

Slide 44

Slide 44 text

Muito obrigado! CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 7/27/19 - 44 / 44 www.galvao.eti.br Dúvidas? Críticas? Elogios?! ? Desenvolvendo APIs com PHP & Expressive