Share
Embed
Desenvolvendo APIs com PHP e Expressive
Teoria e uma demo prática de como desenvolver APIs web usando PHP7 e Expressive.
Er Galvão Abbott
October 19, 2018
Transcript
44 slides
-
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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": "[email protected]" } }, "paths": { "/test": { "get": { "operationId": "getTest", "summary": "Tests the demo", "tags": ["expressive", "demo"], "responses": { "200": { "description": "Test works" } } } } } } Desenvolvendo APIs com PHP & Expressive -
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 -
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 -
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 -
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 -
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott -
7/27/19 - 35 / 44 www.galvao.eti.br Handler <?php declare(strict_types = 1); namespace App\Handler; use Psr\Http\{ Message\ResponseInterface, Message\ServerRequestInterface, Server\RequestHandlerInterface }; use Zend\Diactoros\Response\JsonResponse; class TestHandler implements RequestHandlerInterface { public function handle(ServerRequestInterface $request): ResponseInterface { return new JsonResponse([ 'details' => 'Test success!', ], 200, [ 'X-Powered-By' => 'Expressive Awesomeness!', ]); } } Desenvolvendo APIs com PHP & Expressive -
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 -
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 -
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 -
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott -
7/27/19 - 39 / 44 www.galvao.eti.br <?php return [ 'db' => [ 'driver' => 'Pdo_Mysql', 'database' => 'expressive_demo', 'username' => 'usuario', 'password' => 'senha', ], ]; Configuração config/autoload/database.local.php Desenvolvendo APIs com PHP & Expressive -
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott -
7/27/19 - 40 / 44 www.galvao.eti.br <?php return [ 'dependencies' => [ '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 -
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott -
7/27/19 - 41 / 44 www.galvao.eti.br <?php declare(strict_types=1); namespace App\Handler; use Psr\Container\ContainerInterface; use Psr\Http\Server\RequestHandlerInterface; use Zend\Expressive\Router\RouterInterface; use Zend\Expressive\Template\TemplateRendererInterface; class TestHandlerFactory { public function __invoke(ContainerInterface $container) : RequestHandlerInterface { $router = $container->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 -
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 -
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 -
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